Solved

Issues with Django admin (python)

Posted on 2011-09-30
16
850 Views
Last Modified: 2012-05-12
My project is located at:
/var/www/jobs/myproject/src/MyProject/settings.py

Open in new window


My WSGI:
/var/www/jobs/myproject/public_html/django.wsgi:

import os
import sys

path = '/var/www/jobs/myproject/src'
if path not in sys.path:
    sys.path.append(path)

os.environ['DJANGO_SETTINGS_MODULE'] = 'MyProject.settings'

import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

Open in new window


My admin.py:
/var/www/jobs/myproject/src/MyProject/myproject/admin.py
from MyProject.myproject.models import Supplier 
from django.contrib import admin

admin.site.register(Supplier)

Open in new window


When I access my website (mp.mysite.com) it shows Django's default debug screen.
When I access mp.mysite.com/admin it gives me an error 500:
mod_wsgi (pid=32188): Exception occurred processing WSGI script '/var/www/jobs/myproject/public_html/django.wsgi'.
Traceback (most recent call last):
  File "/usr/lib/python2.4/site-packages/django/core/handlers/wsgi.py", line 241, in __call__
    response = self.get_response(request)
  File "/usr/lib/python2.4/site-packages/django/core/handlers/base.py", line 141, in get_response
    return self.handle_uncaught_exception(request, resolver, sys.exc_info())
  File "/usr/lib/python2.4/site-packages/django/core/handlers/base.py", line 165, in handle_uncaught_exception
    return debug.technical_500_response(request, *exc_info)
  File "/usr/lib/python2.4/site-packages/django/views/debug.py", line 58, in technical_500_response
    html = reporter.get_traceback_html()
  File "/usr/lib/python2.4/site-packages/django/views/debug.py", line 137, in get_traceback_html
    return t.render(c)
  File "/usr/lib/python2.4/site-packages/django/template/__init__.py", line 173, in render
    return self._render(context)
  File "/usr/lib/python2.4/site-packages/django/template/__init__.py", line 167, in _render
    return self.nodelist.render(context)
  File "/usr/lib/python2.4/site-packages/django/template/__init__.py", line 796, in render
    bits.append(self.render_node(node, context))
  File "/usr/lib/python2.4/site-packages/django/template/debug.py", line 72, in render_node
    result = node.render(context)
  File "/usr/lib/python2.4/site-packages/django/template/debug.py", line 89, in render
    output = self.filter_expression.resolve(context)
  File "/usr/lib/python2.4/site-packages/django/template/__init__.py", line 579, in resolve
    new_obj = func(obj, *arg_vals)
  File "/usr/lib/python2.4/site-packages/django/template/defaultfilters.py", line 697, in date
    return format(value, arg)
  File "/usr/lib/python2.4/site-packages/django/utils/dateformat.py", line 281, in format
    return df.format(format_string)
  File "/usr/lib/python2.4/site-packages/django/utils/dateformat.py", line 30, in format
    pieces.append(force_unicode(getattr(self, piece)()))
  File "/usr/lib/python2.4/site-packages/django/utils/dateformat.py", line 187, in r
    return self.format('D, j M Y H:i:s O')
  File "/usr/lib/python2.4/site-packages/django/utils/dateformat.py", line 30, in format
    pieces.append(force_unicode(getattr(self, piece)()))
  File "/usr/lib/python2.4/site-packages/django/utils/encoding.py", line 66, in force_unicode
    s = unicode(s)
  File "/usr/lib/python2.4/site-packages/django/utils/functional.py", line 206, in __unicode_cast
    return self.__func(*self.__args, **self.__kw)
  File "/usr/lib/python2.4/site-packages/django/utils/translation/__init__.py", line 55, in ugettext
    return real_ugettext(message)
  File "/usr/lib/python2.4/site-packages/django/utils/functional.py", line 55, in _curried
    return _curried_func(*(args+moreargs), **dict(kwargs, **morekwargs))
  File "/usr/lib/python2.4/site-packages/django/utils/translation/__init__.py", line 36, in delayed_loader
    return getattr(trans, real_name)(*args, **kwargs)
  File "/usr/lib/python2.4/site-packages/django/utils/translation/trans_real.py", line 276, in ugettext
    return do_translate(message, 'ugettext')
  File "/usr/lib/python2.4/site-packages/django/utils/translation/trans_real.py", line 266, in do_translate
    _default = translation(settings.LANGUAGE_CODE)
  File "/usr/lib/python2.4/site-packages/django/utils/translation/trans_real.py", line 176, in translation
    default_translation = _fetch(settings.LANGUAGE_CODE)
  File "/usr/lib/python2.4/site-packages/django/utils/translation/trans_real.py", line 159, in _fetch
    app = import_module(appname)
  File "/usr/lib/python2.4/site-packages/django/utils/importlib.py", line 35, in import_module
    __import__(name)
TemplateSyntaxError: Caught ImportError while rendering: No module named staticfiles

Open in new window


What am I missing?
0
Comment
Question by:SidGBF
  • 8
  • 8
16 Comments
 
LVL 16

Expert Comment

by:gelonida
Comment Utility
could you show us your settings.py (of course without db passwords or any other confidential info)
0
 

Author Comment

by:SidGBF
Comment Utility
import os;
import django;

DJANGO_ROOT = os.path.dirname(os.path.realpath(django.__file__))
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': os.path.join(SITE_ROOT, 'db') + '/data.db',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Sao_Paulo'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'pt-br'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'

# Additional locations of static files
STATICFILES_DIRS = (
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '7r3@k@hdogcsy9x*&@000l!7p4ct4m37d#uhp=su)&@*mhprls'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)

ROOT_URLCONF = 'MyProjects.urls'

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    'django.contrib.admindocs',
)

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

Open in new window

0
 
LVL 16

Expert Comment

by:gelonida
Comment Utility
Hmm, It seems I forgot to press the send button a few days ago :-(
So here again .

Your config file looks  OK on a first glance.

Some things I would do though:

run debug server for initial tests
----------------------------------------------

I would use
./manage.py runserver
for the first tests

It's easier to play with as it normally detects, when you edited python files.
It will also automatically serve stati cfiles even if you did not collect them prior to the server start

setup more logging
-----------------------------
Modify the LOGGING settings.

you should add a root logger with leven 'DEBUG' c configure it to log into a log file or to the console
and check whether you find somethign interesting.



setup STATIC_ROOT
-------------------------------------------------------
itshould be an absolute path name to the directory, where the static files shall be
collected to.

So it will initially be empty and only be populated by the ./manage.py script
make sure your web server is configured such, that it will map the STATIC_FILE_URL to this path


collect static files
--------------------------
before running on your web server
./manage.py collectstatic





0
 

Author Comment

by:SidGBF
Comment Utility
I did such things.
The debug is empty, and the problem with "staticfiles" still the same problem. (online)

Also, the admin index works, any other admin is not working (even in runserver)
0
 
LVL 16

Expert Comment

by:gelonida
Comment Utility
One thing I noticed now is, that you forgot to add
myproject to your INSTALLED apps list.

Dependign on your searchpath youhave to add
'myproject'
or
'Myproject.myproject'

to the INSTALLED_APPS list.


Concerning the debug logs:
tYou should see at least some activity on the log file / console (depending on your setup)
It's possible, that you won't see anything interesting, but you should at least see something.


Did you add a root logger (A logger named '') and set tle level to 'DEBUG'?


With attached config you should be able to get log information on stdout if yyou start the server with
./manage.py runserver

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)
        },
        'simple': {
            'format': '%(levelname)s %(module)s
        },
    },
    'handlers': {
        'console': {
            'level':'DEBUG',
            'class':'logging.StreamHandler',
            #'formatter': 'simple'
            'formatter': 'verbose'
        }
    },
    'loggers': {
        # root loggers
        '': {
            'level': 'INFO',
            'handlers': ['console'],
            'propagate': True,
        },
    },
}

Open in new window

0
 

Author Comment

by:SidGBF
Comment Utility
logging.basicConfig(
    level = logging.DEBUG,
    format = '%(asctime)s %(levelname)s %(message)s',
    filename = SITE_ROOT+'/debug.log',
    filemode = 'w'
)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)'
        },
        'simple': {
            'format': '%(levelname)s %(module)s'
        },
    },
    'handlers': {
        'console': {
            'level':'DEBUG',
            'class':'logging.StreamHandler',
            #'formatter': 'simple'
            'formatter': 'verbose'
        }
    },
    'loggers': {
        # root loggers
        '': {
            'level': 'INFO',
            'handlers': ['console'],
            'propagate': True,
        },
    },
}

Open in new window


logs nothing
0
 
LVL 16

Expert Comment

by:gelonida
Comment Utility
I think line 1 to 6 should ne removed.


Did you try to add myproject to INSTALLED_APPS?

0
 

Author Comment

by:SidGBF
Comment Utility
I did, yesterday actually, but now I have this:

[03/Oct/2011 09:24:22] "GET / HTTP/1.1" 200 4058
Traceback (most recent call last):
  File "C:\Python27\lib\logging\__init__.py", line 842, in emit
    msg = self.format(record)
  File "C:\Python27\lib\logging\__init__.py", line 719, in format
    return fmt.format(record)
  File "C:\Python27\lib\logging\__init__.py", line 467, in format
    s = self._fmt % record.__dict__
ValueError: incomplete format
Logged from file base.py, line 142
Traceback (most recent call last):
  File "C:\Python27\lib\logging\__init__.py", line 842, in emit
    msg = self.format(record)
  File "C:\Python27\lib\logging\__init__.py", line 719, in format
    return fmt.format(record)
  File "C:\Python27\lib\logging\__init__.py", line 467, in format
    s = self._fmt % record.__dict__
ValueError: incomplete format
Logged from file base.py, line 142
[03/Oct/2011 09:24:23] "GET /sites/site/ HTTP/1.1" 404 2011
Traceback (most recent call last):
  File "C:\Python27\lib\logging\__init__.py", line 842, in emit
    msg = self.format(record)
  File "C:\Python27\lib\logging\__init__.py", line 719, in format
    return fmt.format(record)
  File "C:\Python27\lib\logging\__init__.py", line 467, in format
    s = self._fmt % record.__dict__
ValueError: incomplete format
Logged from file base.py, line 142

Open in new window


when I
http://127.0.0.1:8000/sites/site/

Open in new window


btw:
urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'GinFacil.views.home', name='home'),
    # url(r'^GinFacil/', include('GinFacil.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    #url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    url(r'^$', include(admin.site.urls)),
)

Open in new window

0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 16

Expert Comment

by:gelonida
Comment Utility
I had typos in my LOGGING section.

    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(module)s %(message)s'
        },
    },

Please retry
0
 

Author Comment

by:SidGBF
Comment Utility
[03/Oct/2011 09:55:06] "GET /ginfacil/supplier/ HTTP/1.1" 404 2032
WARNING 2011-10-03 09:55:06,663 base Not Found: /favicon.ico
WARNING 2011-10-03 09:55:11,101 base Not Found: /favicon.ico
WARNING 2011-10-03 09:55:12,105 base Not Found: /auth/group/
[03/Oct/2011 09:55:12] "GET /auth/group/ HTTP/1.1" 404 2011
WARNING 2011-10-03 09:55:12,134 base Not Found: /favicon.ico
WARNING 2011-10-03 09:55:34,448 base Not Found: /auth/group/
[03/Oct/2011 09:55:34] "GET /auth/group/ HTTP/1.1" 404 2011
WARNING 2011-10-03 09:55:34,496 base Not Found: /favicon.ico

Open in new window


It must be a joke...
0
 
LVL 16

Expert Comment

by:gelonida
Comment Utility
Please look at attached project.

Just run:

./manage.py syncdb
to create the data abse and an account allowing to log in
and run then
./manage.py runserver

Then take your browser and connect to:
http://localhost:8000/mypjt/admin/myapp/

Tested with Django 1.3 on Linux and windows.

Please tell me if this example works.

You should be able to administrate mytables
minidjango.zip
0
 

Author Comment

by:SidGBF
Comment Utility
Django version 1.3, using settings 'minidjango.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
INFO 2011-10-03 10:05:26,288 urls urls imported
WARNING 2011-10-03 10:05:26,302 base Not Found: /
[03/Oct/2011 10:05:26] "GET / HTTP/1.1" 404 2108
WARNING 2011-10-03 10:05:26,352 base Not Found: /favicon.ico
WARNING 2011-10-03 10:05:30,757 base Not Found: /
[03/Oct/2011 10:05:30] "GET / HTTP/1.1" 404 2108
WARNING 2011-10-03 10:05:30,813 base Not Found: /favicon.ico
WARNING 2011-10-03 10:05:34,036 base Not Found: /admin
[03/Oct/2011 10:05:34] "GET /admin HTTP/1.1" 404 2123
WARNING 2011-10-03 10:05:34,085 base Not Found: /favicon.ico

Open in new window


Page not found (404)
Request Method:	GET
Request URL:	http://127.0.0.1:8000/admin
Using the URLconf defined in minidjango.urls, Django tried these URL patterns, in this order:
^mypjt/admin/doc/
^mypjt/admin/
The current URL, admin, didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

Open in new window

0
 

Author Comment

by:SidGBF
Comment Utility
Ok, I used the wrong address.
It worked indeed.
0
 
LVL 16

Expert Comment

by:gelonida
Comment Utility
Perhaps you can transform this working example step by step into yours (or vice versa)
I hope it helps to identify why admin is not working for your project, but for the small example.



0
 

Author Comment

by:SidGBF
Comment Utility
I just merged and compared everything.
I can't see any reason for it not working.

Even deactivating my project, using only bundled stuff, it doesn't work!
0
 
LVL 16

Accepted Solution

by:
gelonida earned 500 total points
Comment Utility
Well you have the proof,that your installation is correct, as my example is working.

I would go step by step from a working example to a broken example.
Then you see, which step broke your setup.


One more thing to look at:

This line in urls.py looks very wrong and might be the culprit.
url(r'^$', include(admin.site.urls))
the regular expression matches only for an empty url (  no characters between beginning and end)

You see in my example, that
I used a prefix:
    url(r'^mypjt/admin/', include(admin.site.urls)),

you can always use a redirecrt rule like:
l(r'^?$', redirect_to, {'url': '/mypjt/admin/'}),

if you want to access the admin interface as 'main' interface.
0

Featured Post

Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

Join & Write a Comment

Variable is a place holder or reserved memory locations to store any value. Which means whenever we create a variable, indirectly we are reserving some space in the memory. The interpreter assigns or allocates some space in the memory based on the d…
Introduction On September 29, 2012, the Python 3.3.0 was released; nothing extremely unexpected,  yet another, better version of Python. But, if you work in Microsoft Windows, you should notice that the Python Launcher for Windows was introduced wi…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now