Django: static files in a 404 template
-
16-02-2021 - |
题
How to include stylesheets and images into a 404 page template using the default view?
I created a 404.html
file in the root of the site's templates
directory:
<!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. The 404.css
file is located in one of the apps' static
directory.
The server is 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.
解决方案
It appears, staticfiles
app does work with DEBUG = False
. Only it doesn’t pick up files from individual apps’ static
directories. It would serve files from the global STATIC_ROOT
directory (from settings.py
).
To get the static files copied to STATIC_ROOT
, you need to run the collectstatic
command:
python manage.py collectstatic
其他提示
As contest_processor.static is in the TEMPLATE_CONTEXT already! you can just use the variable STATIC_URL in your template: follow doc:
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.
And we also know that the 404 view handler use a RequestContext Object, follow code took from 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!
When I'm using DEBUG=True, I usually have this snippet in my root urlconf:
(r'^static/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.STATIC_ROOT}),