Django admin causing AttributeError

喜欢而已 提交于 2019-12-10 17:57:13

问题


I am learning Django using the Django Book. I am running python3.3.3 on my Macbook Pro with Mavericks 10.9 and when I enable the admin site I get "A server error occurred. Please contact the administrator." in the browser an "AttributeError: 'RegexURLResolver' object has no attribute '_urlconf_module'" error from the Django server. I have checked (and posted) my settings.py and urls.py files and don't see any issues there...

I found a similar item on GIT here, but I don't believe it applies to what is happening with me. I thought it might be a Mavericks issue, so I ran all the brew updates and the pip upgrade for django, but I am still getting this error...

Any ideas anyone?

Porta-PuterTwo:LearningDjango arana$ python3 manage.py runserver
Validating models...

0 errors found
December 03, 2013 - 21:42:20
Django version 1.6, using settings 'LearningDjango.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Traceback (most recent call last):
  File "/usr/local/lib/python3.3/site-packages/django/core/urlresolvers.py", line 339, in urlconf_module
    return self._urlconf_module
AttributeError: 'RegexURLResolver' object has no attribute '_urlconf_module'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.3/site-packages/django/core/handlers/base.py", line 101, in get_response
    resolver_match = resolver.resolve(request.path_info)
  File "/usr/local/lib/python3.3/site-packages/django/core/urlresolvers.py", line 318, in resolve
    for pattern in self.url_patterns:

urls.py:

from django.conf.urls import patterns, include, url
from LearningDjango.views import currentDatetime

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    url(r'^$', 'LearningDjango.views.home', name='home'),
    url(r'^time/$', currentDatetime),
    # url(r'^blog/', include('blog.urls')),

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

settings.py:

"""
Django settings for LearningDjango project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#6wow&islp6!6@+$9b%j9@981k^@i_uf8^=u%7gp@0b_^j^6t9'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = (
     'django.contrib.admin',
     'django.contrib.auth',
     'django.contrib.contenttypes',
     'django.contrib.messages',
     'django.contrib.sessions',
     'django.contrib.staticfiles',
    'books',
)

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

ROOT_URLCONF = 'LearningDjango.urls'

WSGI_APPLICATION = 'LearningDjango.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '',
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'EST'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_URL = '/static/'

TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)

回答1:


I ran into this error when trying to run a test module residing outside my django project (a practice django doesn't seem to support):

$ tree
.
├── example_project
│   ├── example_app
│   │   ├── __init__.py
│   │   └── models.py
│   ├── __init__.py
│   ├── manage.py
│   └── project
│       ├── __init__.py
│       ├── settings.py
│       ├── urls.py
│       └── wsgi.py
└── test
    └── test_example_app.py

The error was caused by django assuming a different import path at different points in the process so I resolved it by appending to sys.path. I'd be hesitant to do this in a production environment but I can accept some hackiness in tests.

Here's what I ended up with in test_example_app.py:

import os
import sys

import django
from django.conf import settings
from django.test import LiveServerTestCase
from django.test.utils import get_runner

class TestExampleApp(LiveServerTestCase):
   ...

if __name__ == '__main__':
    sys.path.append(os.path.realpath('./example_project'))
    os.environ['DJANGO_SETTINGS_MODULE'] = 'example_project.project.settings'
    django.setup()

    sys.path.append(os.path.realpath('./example_project/project'))
    testrunner = get_runner(settings)()
    failures = testrunner.run_tests(['test_example_app'])
    sys.exit(bool(failures))



回答2:


The solution, as strange as it seems to me, was I had specified the root folder as the start of the import for books.models in the views.py file. This seemed not just to blow up the admin start, but the error that it gave didn't give much, if any, indication of the root issue. It was only when I rolled back to python 2.7 that the error message gave me some indication of the root of the problem. I'm guessing that this is classic neophyte stuff, since it now seems obvious that the 'root' of the site should be the folder with manage.py in it, and therefore shouldn't be in any path specification. Although the book doesn't seem to state that...



来源:https://stackoverflow.com/questions/20366055/django-admin-causing-attributeerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!