使用virtualenv运行应用程序时,设置没有属性ROOT_URLCONF错误

时间:2016-07-19 17:21:56

标签: django settings

我向Django devserver发出请求时遇到错误(它在虚拟环境dj_venv中运行):

[19/Jul/2016 11:32:40] "GET / HTTP/1.1" 500 59
Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/home/daria/venvs/dj_venv/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__
    return self.application(environ, start_response)
  File "/home/daria/venvs/dj_venv/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 241, in __call__
    response = self.get_response(request)
  File "/home/daria/venvs/dj_venv/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 82, in get_response
    urlconf = settings.ROOT_URLCONF
  File "/home/daria/venvs/dj_venv/local/lib/python2.7/site-packages/django/utils/functional.py", line 185, in inner
    return func(self._wrapped, *args)
AttributeError: 'Settings' object has no attribute 'ROOT_URLCONF'

奇怪的是,当我启动服务器并且没有提出任何请求时,我没有收到任何错误:

  

daria @daria:〜/ cms.media $。 ../ venvs / dj_venv / bin中/激活

     

(dj_venv)daria @daria:〜/ cms.media $ python manage.py runserver验证   模型...

     发现Django 1.4.11版错误,使用设置' apps.settings'   开发服务器正在http://127.0.0.1:8000/运行退出   服务器与CONTROL-C。

但是在第一次请求之后我得到了如上所述的AttributeError。

我理解这个错误是因为我的设置对象没有属性' ROOT_URLCONF',但我在settings.py和我的虚拟环境的global_settings.py中定义了它。我也看过这些文章:

1)官方文档(ROOT_URLCONF optionhow Django processes a request

2)相关主题:

我检查了这几点:

1)DJANGO_SETTING_MODULE在manage.py中定义(指向apps.settings)

2)ROOT_URLCONF在settings.py中定义(指向apps文件夹中的外部urls.py)

3)DJANGO_SETTING_MODULE和ROOT_URLCONF被添加到PyCharm的Run>编辑配置>环境变量

有环境变量:

DEFAULT_INDEX_TABLESPACE=1
DJANGO_SETTINGS_MODULE=apps.settings
PYTHONUNBUFFERED=1
ROOT_URLCONF=urls

有我的项目结构:

.
├── apps
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── wsgi.py
│   └── webapp
│       ├── context_processors.py
│       ├── defaults.py
│       ├── __init__.py
│       ├── models.py
│       ├── templates
│       │   └── ...
│       ├── urls.py
│       └── views.py
├── manage.py
└── ...

另外,setting.py定义了ROOT_URLCONF:

import os
import sys
from django.utils.translation import ugettext_noop as _
from django import template

DEBUG = True
# turn off for the perfomance in the production server
TEMPLATE_DEBUG = DEBUG

#USE_TZ = False
#TIME_ZONE = 'Europe/Moscow'

LANGUAGE_CODE = 'ru'
USE_I18N = True
USE_L10N = True


############
# SPICY App

APP_VERSION = '2.0'
AJAX_API_VERSION = '1.0'

# deprecated
MESSAGES = {'success': _('Changes were successfully saved.'),
            'error': _('Please, correct the errors below.')}

APP_SOURCE_PATH = 'apps/'
PROJECT_ROOT = os.path.abspath('.')
ADDITIONAL_PYTHON_PATH = [
    os.path.join(PROJECT_ROOT, APP_SOURCE_PATH),
]

############
# SITESKIN & STATIC
SITE_ID = 1
USE_CUSTOM_ADMIN = True
# deprecated
SITESKIN = ''
AJAX_ACCESS_CONTROL_ALLOW_ORIGIN = '*.localhost'
CACHE_PREFIX = '%s-' % SITESKIN
CACHE_BACKEND = 'locmem://'

###################
# PROFILE

LOGIN_REDIRECT_URL = '/'
LOGIN_URL = '/signin/'
REGISTRATION_OPEN = True
SECRET_KEY = 'lalala'
LOGIN_URL = '/signin/'
LOGIN_REDIRECT_URL = '/'

AUTHENTICATION_BACKENDS = (
    'spicy.core.profile.auth_backends.CustomUserModelBackend',
)
USE_CAPTCHA = False
USE_FEEDBACK_CAPTCHA = False
CAPTCHA_CHALLENGE_FUNCT = 'captcha.helpers.math_challenge'
CAPTCHA_NOISE_FUNCTIONS = ()
#('captcha.helpers.noise_arcs','captcha.helpers.noise_dots',)

...

###############
## DJANGO

ADMINS = (
    # ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        }
}
#CACHE_BACKEND = 'memcached://127.0.0.1:11311/'#'locmem:///'
CACHE_TIMEOUT = 1*60 # seconds

SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_ENGINE = "django.contrib.sessions.backends.cached_db"
SESSION_SAVE_EVERY_REQUEST = True
#SESSION_COOKIE_DOMAIN = ''

STATIC_URL = '/static/'
THEMES_PATH = os.path.abspath('..')

try:
    from config import *
except ImportError, msg:
    raise ImportError, 'Using default config settings, check "config" directory.\n'

for _path in ADDITIONAL_PYTHON_PATH:
    sys.path.insert(0, os.path.abspath(_path))

## deprecated
# while SITESKIN exists

STATIC_ROOT = os.path.abspath('../static/')

## deprecated

SERVICES = (
    'spicy.core.profile.services.ProfileService',
    'spicy.core.trash.services.TrashService',
    'spicy.mediacenter.services.MediaService',
    'spicy.mediacenter.services.LibraryService',
    'spicy.history.services.HistoryService',
    'spicy.xtag.services.TagService',
    'spicy.ratings.services.RatingService',
)

LOCALE_PATHS = (os.path.join(PROJECT_ROOT, 'locale'), )

#TEST_RUNNER = 'django_nose.runner.NoseTestSuiteRunner'
#NOSE_ARGS = ['-v', '--with-color']

ROOT_URLCONF = 'apps.urls'

STATICFILES_FINDERS = (
    'spicy.core.siteskin.loaders.ThemeStaticFinder',
    'spicy.core.siteskin.loaders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',                                                                                                                                                             
)

TEMPLATE_LOADERS = (
    'spicy.core.siteskin.loaders.ThemeTemplateLoader',
    'django.template.loaders.app_directories.Loader',
    'spicy.core.siteskin.loaders.BackendTemplateLoader',
)

template.add_to_builtins('django.templatetags.i18n')


TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',

    'spicy.core.profile.context_processors.auth',
    'spicy.core.siteskin.context_processors.base',
    'spicy.core.admin.context_processors.base',

    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.media',
    'django.core.context_processors.request',

    'apps.webapp.context_processors.site_content',
    )

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    #'django.middleware.locale.LocaleMiddleware', - don't use it =)
    'django.middleware.common.CommonMiddleware',

    'spicy.core.profile.middleware.AuthMiddleware',

    'django.middleware.doc.XViewMiddleware',

    # XXX is it required ??
    'spicy.core.siteskin.middleware.AjaxMiddleware',
    'spicy.core.siteskin.threadlocals.ThreadLocals',
)

if DEBUG:
    MIDDLEWARE_CLASSES += (
        # for developers
        'spicy.core.rmanager.middleware.ProfileMiddleware',
    )


INSTALLED_APPS = [
    # Django admin
    'django.contrib.admin',

    # Django native apps
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.humanize',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.staticfiles',

    # Application
    'apps.webapp',

    # Spicy core components
    'spicy.core.admin',
    'spicy.core.service',
    'spicy.core.siteskin',
    'spicy.core.simplepages',

    # Spicy apps
    'spicy.presscenter',
    'spicy.categories',
    'spicy.mediacenter',
    'spicy.core.profile',
    'spicy.feedback',
#    'spicy.labels',
    'spicy.seo',
    'spicy.xtag',

    # 'django_nose',
    # 'captcha',
    'sorl.thumbnail',
    'pytils',
    'raven.contrib.django.raven_compat',
]

# 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 when DEBUG=False.                                                                                                                                                                 
# 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': True,
    'formatters': {
        'common': {
            'format': '[%(asctime)s][%(levelname)-9s] %(name)s %(filename)s:%(funcName)s:%(lineno)d | %(message)s',
            'datefmt': '%H:%M:%S',
        },
    },
    'handlers': {
        'null': {
            'level': 'DEBUG',
            'class': 'django.utils.log.NullHandler',
        },
        'console':{
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'common'
        },
        # 'sentry': {
        #     'level': 'INFO',
        #     'class': 'raven.handlers.logging.SentryHandler',
        #     'dsn': '{{ spicy.config.sentry }}',
        # }
    },
    'loggers': {
        '': {
            'handlers': ['console'],
            'propagate': True,
            'level': 'INFO',
        },
        'django': {
            'handlers': ['console'],
            'propagate': True,
            'level': 'INFO',
        },
        'django.request': {
            'handlers': ['console'],
            'level': 'ERROR',
            'propagate': False,
        },
    }
}



# App custom models

#CUSTOM_USER_MODEL = ''
CUSTOM_DOCUMENT_MODEL = 'webapp.Document'
#LABELS_CONSUMER = CUSTOM_DOCUMENT_MODEL

#CUSTOM_MEDIA_MODEL = 'blog.BlogMedia'
#CUSTOM_MEDIA_PROVIDER_MODEL = 'blog.BlogMediaProvider'

并且manage.py:

#!/usr/bin/env python                                                                                                                                                                                 
import os, sys
from importlib import import_module

os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'apps.settings')

from django.conf import settings
from django.core.management import execute_from_command_line

execute_from_command_line(sys.argv)

外部urls.py(./apps / urls.py):

from django.conf.urls.defaults import include, patterns, url
from django.conf import settings
from spicy import utils

from django.contrib import admin

admin.autodiscover()

handler404 = 'spicy.core.siteskin.views.page_not_found'
handler500 = 'spicy.core.siteskin.views.server_error'
handler403 = 'spicy.core.siteskin.views.forbidden'

urlpatterns = patterns(
    '',
    url(r'^django/', include(admin.site.urls)),
    url(r'^', include('spicy.core.admin.urls', namespace='spicyadmin')),
    url(r'^captcha/', include('captcha.urls')),
    )

内部urls.py(./apps / webapp / urls.py):

from django.conf.urls.defaults import *

public_urls = patterns(
    '',
    )

public_urls += patterns(
    url(r'^create/$', 'create_article', name='create'),
    url(r'^a(?P<doc_id>\d+)/$', 'document', name='doc'),
    url(r'^a(?P<doc_id>\d+)/edit/$', 'edit_article', name='edit'),
    )

urlpatterns = patterns(
    '',
    url(r'^', include(public_urls, namespace='public'))
    )

这种例外可能是什么原因?我已经尝试了在stackoverflow中找到的所有内容。我想原因可能是对settings.py或ROOT_URLCONF的错误引用,我尝试了各种选择,但我仍然遇到属性错误。

而且我猜想原因可能是中间件可能会在服务器执行请求时重新定义ROOT_URLCONF(因为在我不向服务器发出任何请求之前它是可以的),但是我并没有这样做。我知道在哪里可以解决它。

我猜对了吗?如果是,我该如何解决我的问题?希望有任何帮助!

1 个答案:

答案 0 :(得分:0)

您似乎必须在INSTALLED_APPS注册您的应用(显然称为&#34;应用&#34;)。

此外,您在apps.urls设置ROOT_URLCONF,但在环境值上设置urls(不包含apps.部分)