调试=False时Django服务器错误未解析路径

2024-09-30 14:37:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行一个使用Django cookie cutter构建的应用程序(Django 2.1,但我在类似的Django 3.0项目中也收到了相同的错误),它在DEBUG = True时工作得非常好。只要我打开DEBUG = False,我就会收到这个递归错误消息,然后服务器崩溃说A server error occurred. Please contact the administrator(这取决于我测试的位置,但基本上说响应不完整)

WARNING 2020-11-01 08:36:43,217 loader_tags 17863 123145445117952 Exception raised while rendering {% include %} for template '404.html'. Empty string rendered instead.
Traceback (most recent call last):
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    resolver_match = resolver.resolve(request.path_info)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/urls/resolvers.py", line 523, in resolve
    raise Resolver404({'tried': tried, 'path': new_path})
django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <URLResolver list> (None:None) 'en-us/'>], [<URLResolver <module 'config.api_router' from '/Users/kevin/projects/cdsso/config/api_router.py'> (api:api) 'api/'>]], 'path': 'join/'}

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/core/handlers/exception.py", line 99, in get_exception_response
    response = callback(request, **dict(param_dict, exception=exception))
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/utils/decorators.py", line 142, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/views/defaults.py", line 46, in page_not_found
    body = template.render(context, request)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render
    return self.template.render(context)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/base.py", line 175, in render
    return self._render(context)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/test/utils.py", line 98, in instrumented_test_render
    return self.nodelist.render(context)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/base.py", line 943, in render
    bit = node.render_annotated(context)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/base.py", line 910, in render_annotated
    return self.render(context)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/loader_tags.py", line 155, in render
    return compiled_parent._render(context)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/test/utils.py", line 98, in instrumented_test_render
    return self.nodelist.render(context)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/base.py", line 943, in render
    bit = node.render_annotated(context)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/base.py", line 910, in render_annotated
    return self.render(context)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/loader_tags.py", line 67, in render
    result = block.nodelist.render(context)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/base.py", line 943, in render
    bit = node.render_annotated(context)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/base.py", line 910, in render_annotated
    return self.render(context)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/defaulttags.py", line 314, in render
    return nodelist.render(context)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/base.py", line 943, in render
    bit = node.render_annotated(context)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/base.py", line 910, in render_annotated
    return self.render(context)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/defaulttags.py", line 447, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/urls/base.py", line 88, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/urls/resolvers.py", line 632, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'register' not found. 'register' is not a valid view function or pattern name.

它重复django.urls.exceptions.NoReverseMatch: Reverse for 'register' not found直到崩溃。这是我的基本设置文件(此错误在生产和本地都会发生):

"""
Base settings to build other settings files upon.
"""
import environ
from django.utils.translation import ugettext_lazy as _
from pathlib2 import Path

ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent.parent
# cdsso/
APPS_DIR = ROOT_DIR / "cdsso"
env = environ.Env()

READ_DOT_ENV_FILE = env.bool("DJANGO_READ_DOT_ENV_FILE", default=True)
if READ_DOT_ENV_FILE:
    # OS environment variables take precedence over variables from .env
    env.read_env(str(ROOT_DIR / ".env"))

# GENERAL
# ------------------------------------------------------------------------------
# 
DEBUG = env.bool("DJANGO_DEBUG", False)
# Local time zone. Choices are
# 
# though not all of them may be available with every OS.
# In Windows, this must be set to your system time zone.
TIME_ZONE = "UTC"
# 
LANGUAGE_CODE = env("DJANGO_LANGUAGE_CODE", default="en-us")

LANGUAGES = [
    ("es", _("Spanish")),
    ("en-us", _("English")),
    ("fr", _("French")),
    ("ar", _("Arabic")),
    ("nl", _("Dutch")),
    ("ge", _("German")),
    ("ja", _("Japanese")),
    ("hi", _("Hindi")),
]

SITE_ID = 1
USE_I18N = True
USE_L10N = True
USE_TZ = True
LOCALE_PATHS = [str(ROOT_DIR / "locale")]

# DATABASES
# ------------------------------------------------------------------------------

DATABASES = {"default": env.db("DATABASE_URL", default="mysql:///codedevils_weblogin")}
DATABASES["default"]["ATOMIC_REQUESTS"] = True

# URLS
# ------------------------------------------------------------------------------
ROOT_URLCONF = "config.urls"
# https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = "config.wsgi.application"

# APPS
# ------------------------------------------------------------------------------
DJANGO_APPS = [
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.sites",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.admin",
    "django.forms",
]
THIRD_PARTY_APPS = [
    "crispy_forms",
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "allauth.socialaccount.providers.keycloak",
    "cas_server",
    "django_celery_beat",
    "drf_yasg",
    "graphene_django",
    "rest_framework",
    "rest_framework.authtoken",
    "rosetta",
]

LOCAL_APPS = [
    "cdsso.users.apps.UsersConfig",
    "cdsso.contrib.countries.apps.CountriesConfig",
    "cdsso.contrib.register.apps.RegisterConfig",
]

INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + LOCAL_APPS

# MIGRATIONS
# ------------------------------------------------------------------------------
MIGRATION_MODULES = {"sites": "cdsso.contrib.sites.migrations"}

# AUTHENTICATION
# ------------------------------------------------------------------------------
AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
]
AUTH_USER_MODEL = "users.User"
LOGIN_REDIRECT_URL = env("CDSSO_LOGIN_REDIRECT_URL", default="register:status")
LOGIN_URL = "cas_server:login"
LOGOUT_REDIRECT_URL = LOGIN_URL

# PASSWORDS
# ------------------------------------------------------------------------------
PASSWORD_HASHERS = [
    # https://docs.djangoproject.com/en/dev/topics/auth/passwords/#using-argon2-with-django
    "django.contrib.auth.hashers.Argon2PasswordHasher",
    "django.contrib.auth.hashers.PBKDF2PasswordHasher",
    "django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
    "django.contrib.auth.hashers.BCryptSHA256PasswordHasher",
]
AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"
    },
    {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator"},
    {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator"},
    {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator"},
]

# MIDDLEWARE
# ------------------------------------------------------------------------------
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.locale.LocaleMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.common.BrokenLinkEmailsMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "cdsso.contrib.register.middleware.UserRegistrationConfirmationMiddleware",
    "config.middleware.LanguageIdenitifcationMiddleware",
]

# STATIC
# ------------------------------------------------------------------------------
STATIC_ROOT = str(APPS_DIR / "staticfiles")
STATIC_URL = "/static/"
STATICFILES_DIRS = [str(ROOT_DIR / "public/static")]
STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
]

# MEDIA
# ------------------------------------------------------------------------------
MEDIA_ROOT = str(ROOT_DIR / "public/media")
MEDIA_URL = "/media/"

# TEMPLATES
# ------------------------------------------------------------------------------
TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [str(APPS_DIR / "templates")],
        "OPTIONS": {
            "loaders": [
                "django.template.loaders.filesystem.Loader",
                "django.template.loaders.app_directories.Loader",
            ],
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.template.context_processors.i18n",
                "django.template.context_processors.media",
                "django.template.context_processors.static",
                "django.template.context_processors.tz",
                "django.contrib.messages.context_processors.messages",
                "cdsso.utils.context_processors.settings_context",
            ],
        },
    }
]

FORM_RENDERER = "django.forms.renderers.TemplatesSetting"

CRISPY_TEMPLATE_PACK = "bootstrap4"

# FIXTURES
# ------------------------------------------------------------------------------
FIXTURE_DIRS = (str(APPS_DIR / "fixtures"),)

# SECURITY
# ------------------------------------------------------------------------------
SESSION_COOKIE_HTTPONLY = True
CSRF_COOKIE_HTTPONLY = True
SECURE_BROWSER_XSS_FILTER = True
X_FRAME_OPTIONS = "DENY"

# EMAIL
# ------------------------------------------------------------------------------
EMAIL_BACKEND = env(
    "DJANGO_EMAIL_BACKEND", default="django.core.mail.backends.smtp.EmailBackend"
)
# ADMIN
# ------------------------------------------------------------------------------
# Django Admin URL.
ADMIN_URL = "admin/"
ADMINS = [("""Kevin Shelley""", "xxxxxxx@xxxxx.xxx")]
MANAGERS = ADMINS

# LOGGING
# ------------------------------------------------------------------------------
LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "verbose": {
            "format": "%(levelname)s %(asctime)s %(module)s "
            "%(process)d %(thread)d %(message)s"
        }
    },
    "handlers": {
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "verbose",
        },
        "debug": {
            "level": "INFO",
            "class": "logging.FileHandler",
            "filename": "error.log",
            "formatter": "verbose"
        }
    },
    "root": {"level": "DEBUG", "handlers": ["console", "debug"]},
}

# Celery
# ------------------------------------------------------------------------------
if USE_TZ:
    CELERY_TIMEZONE = TIME_ZONE
CELERY_BROKER_URL = env("CELERY_BROKER_URL")
CELERY_RESULT_BACKEND = CELERY_BROKER_URL
CELERY_ACCEPT_CONTENT = ["json"]
CELERY_TASK_SERIALIZER = "json"
CELERY_RESULT_SERIALIZER = "json"
CELERY_TASK_TIME_LIMIT = 5 * 60
CELERY_TASK_SOFT_TIME_LIMIT = 60
CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler"
# django-allauth
# ------------------------------------------------------------------------------
ACCOUNT_ALLOW_REGISTRATION = env.bool("DJANGO_ACCOUNT_ALLOW_REGISTRATION", True)
ACCOUNT_AUTHENTICATION_METHOD = "username_email"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "mandatory"
ACCOUNT_ADAPTER = "cdsso.users.adapters.AccountAdapter"
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 3
ACCOUNT_EMAIL_REQUIRED = True
SOCIALACCOUNT_ADAPTER = "cdsso.users.adapters.SocialAccountAdapter"
ACCOUNT_FORMS = {"signup": "cdsso.contrib.register.forms.StudentRegistrationForm"}

# django-rest-framework
# -------------------------------------------------------------------------------
REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework.authentication.SessionAuthentication",
        "rest_framework.authentication.TokenAuthentication",
    ),
    "DEFAULT_PERMISSION_CLASSES": ("rest_framework.permissions.IsAuthenticated",),
}

# django-cas-server
# -------------------------------------------------------------------------------
# CAS_FEDERATE = True
CAS_LOGO_URL = False
CAS_FAVICON_URL = False
CAS_SHOW_POWERED = False
CAS_SHOW_SERVICE_MESSAGES = False
CAS_LOGIN_TEMPLATE = "cas/login.html"
CAS_WARN_TEMPLATE = "cas/warn.html"
CAS_LOGOUT_TEMPLATE = "cas/logout.html"
CAS_LOGGED_TEMPLATE = "cas/logged.html"

和我的基本urls.py文件:

from django.conf import settings
from django.conf.urls.i18n import i18n_patterns
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path
from django.views import defaults as default_views

urlpatterns = i18n_patterns(
    # Django Admin, use {% url 'admin:index' %}
    path(settings.ADMIN_URL, admin.site.urls),
    # django-simple-sso
    path("cas/", include("config.cas", namespace="cas_server")),
    # user management
    path("users/", include("cdsso.users.urls", namespace="users")),
    path("accounts/", include("allauth.urls")),
    path("join/", include("cdsso.contrib.register.urls", namespace="register")),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

# API URLS
urlpatterns += [
    # API base url
    path("api/", include("config.api_router"))
]

if settings.DEBUG:
    # This allows the error pages to be debugged during development, just visit
    # these url in browser to see how these error pages look like.
    urlpatterns += [
        path(
            "400/",
            default_views.bad_request,
            kwargs={"exception": Exception("Bad Request!")},
        ),
        path(
            "403/",
            default_views.permission_denied,
            kwargs={"exception": Exception("Permission Denied")},
        ),
        path(
            "404/",
            default_views.page_not_found,
            kwargs={"exception": Exception("Page not Found")},
        ),
        path("500/", default_views.server_error),
    ]
    if "debug_toolbar" in settings.INSTALLED_APPS:
        import debug_toolbar

        urlpatterns = [path("__debug__/", include(debug_toolbar.urls))] + urlpatterns

    if "rosetta" in settings.INSTALLED_APPS:

        urlpatterns = i18n_patterns(path("rosetta", include("rosetta.urls"))) + urlpatterns

到目前为止,我已经尝试:

  • urls.py中删除i18n_patterns。我仍然在未找到或缓存的页面上收到错误
  • 添加DEBUG_PROPAGATE_EXCEPTIONS = True。这只会停止递归,但会显示相同的错误消息
  • STATIC_ROOTSTATICFILES_DIRS更改为其他目录。我认为这不是问题所在,因为它根本没有注册我的URL,也没有任何缺少静态资产的迹象

感谢您的帮助!我盯着这个看了好几天都没用


Tags: djangoinpylibcontextsitetemplaterender