[英]Django: static files in a 404 template
How to include stylesheets and images into a 404 page template using the default view? 如何使用默认视图将样式表和图像包含到404页面模板中?
I created a 404.html
file in the root of the site's templates
directory: 我在网站的templates
目录的根目录中创建了一个404.html
文件:
<!DOCTYPE html>
<html>
<head>
{% load static %}
<link rel="stylesheet" href="{% get_static_prefix %}css/404.css" />
</head>
<body class="page-404">
<p>Not found.</p>
</body>
</html>
Ironically, the 404.css
is not found. 具有讽刺意味的是, 404.css
。 The 404.css
file is located in one of the apps' static
directory. 404.css
文件位于应用程序的static
目录之一。
The server is manage.py runserver
. 服务器是manage.py runserver
。 On every other page static files are served just well. 在每个其他页面上,静态文件都可以很好地提供。
Update : It appears, after setting DEBUG = False
in the settings.py
, static files on all other pages stopped being served, too. 更新 :在settings.py
设置DEBUG = False
后,所有其他页面上的静态文件也会停止提供。
It appears, staticfiles
app does work with DEBUG = False
. 看来, staticfiles
app确实可以使用DEBUG = False
。 Only it doesn't pick up files from individual apps' static
directories. 只有它不会从各个应用程序的static
目录中获取文件。 It would serve files from the global STATIC_ROOT
directory (from settings.py
). 它将从全局STATIC_ROOT
目录(来自settings.py
)提供文件。
To get the static files copied to STATIC_ROOT
, you need to run the collectstatic
command : 要将静态文件复制到STATIC_ROOT
,您需要运行collectstatic
命令 :
python manage.py collectstatic
As contest_processor.static is in the TEMPLATE_CONTEXT already! 由于contest_processor.static已经在TEMPLATE_CONTEXT中! you can just use the variable STATIC_URL in your template: follow doc: 您可以在模板中使用变量STATIC_URL:按照doc:
https://docs.djangoproject.com/en/1.3/ref/templates/api/#django-core-context-processors-static https://docs.djangoproject.com/en/1.3/ref/templates/api/#django-core-context-processors-static
If TEMPLATE_CONTEXT_PROCESSORS contains this processor, every RequestContext will contain a variable STATIC_URL, providing the value of the STATIC_URL setting. 如果TEMPLATE_CONTEXT_PROCESSORS包含此处理器,则每个RequestContext都将包含一个变量STATIC_URL,提供STATIC_URL设置的值。
And we also know that the 404 view handler use a RequestContext Object, follow code took from django.views.defaults.py: 我们也知道404视图处理程序使用RequestContext对象,请遵循django.views.defaults.py中的代码:
return http.HttpResponseNotFound(t.render(RequestContext(request, {'request_path': request.path})))
So just use {{ STATIC_URL }}
in your template, it should work! 所以只需在模板中使用{{ STATIC_URL }}
,就可以了!
When I'm using DEBUG=True, I usually have this snippet in my root urlconf: 当我使用DEBUG = True时,我通常在我的root urlconf中有这个片段:
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.