当调试在生产中为 False 时,Django 抛出 500
Posted
技术标签:
【中文标题】当调试在生产中为 False 时,Django 抛出 500【英文标题】:Django throws 500 when debug is False in Production 【发布时间】:2021-12-08 15:22:10 【问题描述】:当我使用DEBUG=False
运行时,我无法理解为什么 Django 3 会失败。 url似乎也有问题:
www.domain.com/ -> Does not work
www.domain.com/en/ -> No problem
日志似乎提到了一百万个问题,但我不明白最初的问题是什么,所以我正在寻求帮助:
Exception while resolving variable 'self' in template '404.html'.
Traceback (most recent call last):
File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 167, in _get_response
callback, callback_args, callback_kwargs = self.resolve_request(request)
File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 290, in resolve_request
resolver_match = resolver.resolve(request.path_info)
File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/urls/resolvers.py", line 585, in resolve
raise Resolver404('tried': tried, 'path': new_path)
django.urls.exceptions.Resolver404: 'tried': [[<URLResolver <URLPattern list> (admin:admin) '^django-admin/'>], [<URLResolver <module 'wagtail.admin.urls' from '/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/wagtail/admin/urls/__init__.py'> (None:None) '^admin/'>], [<URLResolver <module 'wagtail.documents.urls' from '/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/wagtail/documents/urls.py'> (None:None) '^documents/'>], [<URLPattern '^i18n/$' [name='set_language']>], [<URLPattern '^sitemap\.xml$'>], [<URLResolver <URLResolver list> (None:None) 'bg/'>]], 'path': ''
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 829, in _resolve_lookup
current = current[bit]
File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'self'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 835, in _resolve_lookup
if isinstance(current, BaseContext) and getattr(type(current), bit):
AttributeError: type object 'RequestContext' has no attribute 'self'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup
current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'self'
#####################
# ...
# Rest of debug lines: https://pastebin.com/5AqDZu11
# ...
#####################
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 837, in _resolve_lookup
current = getattr(current, bit)
AttributeError: 'NoneType' object has no attribute 'url_name'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 843, in _resolve_lookup
current = current[int(bit)]
ValueError: invalid literal for int() with base 10: 'url_name'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/pp/www/SmileDesign/venv/lib/python3.7/site-packages/django/template/base.py", line 850, in _resolve_lookup
(bit, current)) # missing attribute
django.template.base.VariableDoesNotExist: Failed lookup for key [url_name] in None
Internal Server Error: /favicon.ico
"GET /favicon.ico HTTP/1.1" 500 680
我看到底部写着Internal Server Error: /favicon.ico
,我怀疑这是罪魁祸首,但即使我尝试了以下解决方法,问题仍然存在:
url(r'^favicon.ico$', RedirectView.as_view(url=staticfiles_storage.url('img/favicon.ico'), permanent=True)),
我仍然得到 500 结尾:
Internal Server Error: /
"GET / HTTP/1.1" 500 680
"GET /favicon.ico HTTP/1.1" 301 0
"GET /static/img/favicon.be884a05bb00.ico HTTP/1.1" 200 9896
通过查看第一行,404.html
似乎存在问题
% extends "base.html" %
% block body_class %template-404% endblock %
% block content %
<h1>Page not found</h1>
<h2>Sorry, this page could not be found.</h2>
% endblock %
如果我删除扩展base.html的行,它会运行,但我不清楚为什么。
% load static wagtailuserbar %
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
<script type="text/javascript" src="% static 'js/is-mobile.min.js' %"></script>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>
% block title %
% if self.seo_title %
self.seo_title
% elif self.translated_title %
self.translated_title
% else %
self.title
% endif %
% endblock %
% block title_suffix %
% with self.get_site.site_name as site_name %
% if site_name %- site_name % endif %
% endwith %
% endblock %
</title>
<link rel="shortcut icon" href="% static 'img/favicon.ico' %">
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="% block meta_description %% endblock %" />
<meta name="keywords" content="% block meta_keywords %% endblock %" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="% static 'slick/slick.css' %"/>
# Global stylesheets #
% if debug %
<link rel="stylesheet" type="text/css" href="% static 'css/main.css' %">
% else %
<link rel="stylesheet" type="text/css" href="% static 'css/main.min.css' %">
% endif %
% if not request.is_preview %
# The page is not in preview mode #
# Put google analytics, mixpanel, etc... here #
% endif %
% block extra_css %
# Override this in templates to add extra stylesheets #
% endblock %
</head>
<body class="% block body_class %% endblock %">
% wagtailuserbar %
% block navigation %
% include 'partials/_navigation.html' %
% endblock %
<div class="content">% block content %% endblock %</div>
% block footer %
% include 'partials/_footer.html' %
% endblock %
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script type="text/javascript" src="% static 'slick/slick.min.js' %"></script>
<script src="https://unpkg.com/scrollreveal@3.3.5/dist/scrollreveal.min.js"></script>
<script type="text/javascript" src="% static 'js/parallax.min.js' %"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/parallax/3.1.0/parallax.min.js"></script>
<script id="developedby" data-client-id="d640d636-cbe0-493c-b51a-124becd2cd6d" src="https://hakomo.s3.eu-central-1.amazonaws.com/static/js/webdevelopmentbyhakomo.js"></script>
<script src="% static 'js/min/main.js' %"></script>
% block extra_js %
# Override this in templates to add extra javascript #
% endblock %
</body>
</html>
我的 urls.py:
urlpatterns = [
url(r'^django-admin/', admin.site.urls),
url(r'^admin/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
url(r'^i18n/$', set_language, name='set_language'),
url(r'^sitemap\.xml$', sitemap, sitemaps),
url(r'^favicon.ico$', RedirectView.as_view(url=staticfiles_storage.url('img/favicon.ico'), permanent=True)),
]
urlpatterns += i18n_patterns(
# These URLs will have /<language_code>/ appended to the beginning
url(r'', include(content_urls)),
url(r'^search/$', search_views.search, name='search'),
url(r'', include(wagtail_urls)),
)
if settings.DEBUG:
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Serve static and media files from development server
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
所以除了理解为什么扩展基础是一个问题之外,
我也想知道为什么我们一开始就得到 404。
感谢您的帮助
【问题讨论】:
问题与模板变量有关。你能展示你的视图,它呈现base.html
【参考方案1】:
第一行说:
Exception while resolving variable 'self' in template '404.html'.
并且您在您的base.html
中使用了self
,因此当您删除时
% extends "base.html" %
一切正常。
所以Django无法解析变量self
,
请使用views.py
更新您的问题,这会将上下文变量self
传递给base.html
这肯定会解决问题
另外,我们应该避免在 Python 中使用保留关键字如 self
作为变量名
【讨论】:
以上是关于当调试在生产中为 False 时,Django 抛出 500的主要内容,如果未能解决你的问题,请参考以下文章
Django 2.2静态文件在生产中不起作用(DEBUG False)[重复]