Django: static files in a 404 template

耗尽温柔 提交于 2019-12-08 12:04:15

问题


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.


回答1:


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



回答2:


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!




回答3:


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}),


来源:https://stackoverflow.com/questions/7946180/django-static-files-in-a-404-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!