Link to home
Start Free TrialLog in
Avatar of SidGBF
SidGBFFlag for Brazil

asked on

Issues with Django admin (python)

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?
Avatar of gelonida
gelonida
Flag of France image

could you show us your settings.py (of course without db passwords or any other confidential info)
Avatar of SidGBF

ASKER

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

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





Avatar of SidGBF

ASKER

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)
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

Avatar of SidGBF

ASKER

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
I think line 1 to 6 should ne removed.


Did you try to add myproject to INSTALLED_APPS?

Avatar of SidGBF

ASKER

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

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
Avatar of SidGBF

ASKER

[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...
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
Avatar of SidGBF

ASKER

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

Avatar of SidGBF

ASKER

Ok, I used the wrong address.
It worked indeed.
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.



Avatar of SidGBF

ASKER

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!
ASKER CERTIFIED SOLUTION
Avatar of gelonida
gelonida
Flag of France image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial