我建立一个应用程序使用Django作为我的主力。到目前为止,一切都很好-指定的数据库设置,配置的静态目录,url,视图等。但是当我想要渲染自己漂亮的自定义404.html和500.html页面时,麻烦就来了。

我阅读了关于自定义错误处理的文档,并在UrlsConf中设置了必要的配置,创建了相应的视图,并将404.html和500.html添加到我的应用程序的模板目录(在settings.py中也指定了)。

但是文档说,在Debug关闭之前,您实际上可以查看自定义错误视图,所以我确实关闭了它来测试我的东西,而那就是事情变得疯狂的时候!

我不仅无法查看自定义404.html(实际上,它加载,但因为我的错误页面每个包含一个图形错误消息-作为一些漂亮的图像),错误页面的源加载,但没有其他加载!甚至没有链接CSS或Javascript!

一般来说,一旦我设置DEBUG = False,所有的视图将加载,但任何链接的内容(CSS, Javascript,图像等)不会加载!发生什么事情了?是否有什么东西我丢失了,关于静态文件和调试设置?


当前回答

Nginx,设置和url配置

如果你在linux上,这可能会有帮助。

nginx 文件

your_machn: / /维姆etc / nginx sites-available / nginxfile

server {
    server_name xyz.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /var/www/your_prj;
    }

    location /media/ {
        root /var/www/your_prj;
    }
...........
......
}

urls . py

.........
   .....
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('test/', test_viewset.TestServer_View.as_view()),
        path('api/private/', include(router_admin.urls)),
        path('api/public/', include(router_public.urls)),    
        ]
    
    if settings.DEBUG:
        import debug_toolbar
        urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
        urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

settings.py

.....
........
STATIC_URL = '/static/'
MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
.....
....

确保运行:

(venv)yourPrj$ ./manage.py collectstatic
yourSys# systemctrl daemon-reload

其他回答

对于Django的最新版本,请查看这里的答案:https://stackoverflow.com/a/7639983/6180987

对于django 1.10以下的版本,解决方案应该工作:

只要打开你的项目urls.py,然后找到这个if语句。

if settings.DEBUG:
    urlpatterns += patterns(
        'django.views.static',
        (r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )

您可以更改设置。DEBUG设为True,它将始终工作。但如果你的项目是一个严重的问题,那么你应该考虑上面提到的其他解决方案。

if True:
    urlpatterns += patterns(
        'django.views.static',
        (r'^media/(?P<path>.*)','serve',{'document_root': settings.MEDIA_ROOT}), )

在django 1.10中,你可以这样写:

urlpatterns += [ url(r'^media/(?P<path>.*)$', serve, { 'document_root': settings.MEDIA_ROOT, }), url(r'^static/(?P<path>.*)$', serve, { 'document_root': settings.STATIC_ROOT }), ]

实际上,你可以在Django生产应用程序中提供静态文件,而且不需要DEBUG=True。

不要使用Django本身,在你的WSGI文件(github)中使用dj_static:

让:

...
dj-static==0.0.6

YOURAPP/settings.py:

...
STATIC_ROOT = 'staticdir'
STATIC_URL = '/staticpath/'

YOURAPP/wsgi.py:

...
from django.core.wsgi import get_wsgi_application
from dj_static import Cling

application = Cling(get_wsgi_application())

这是正常且有意为之的行为。

Warning

This will only work if DEBUG is True.  
you can actually view custom error views until Debug is Off  

如果Django只是从文件系统中读取并发送一个文件,那么它与普通的web服务器相比没有任何优势,所有的web服务器都能够自己提供文件。

此外,如果你用Django提供静态文件,你会让Python进程在请求期间一直很忙,它将无法提供更适合它的动态请求。

由于这些原因,Django静态视图仅设计用于开发期间,如果DEBUG设置为False,则它将无法工作。

因为在开发过程中,我们通常一次只有一个人访问站点 developer), Django可以很好地提供静态文件。

Johnny的回答很好,但仅仅通过添加那里描述的那些行对我来说仍然不适用。根据这个答案,对我有效的步骤是:

Install WhiteNoise as described: pip install WhiteNoise Create the STATIC_ROOT variable and add WhiteNoise to your MIDDLEWARE variable in settings.py: #settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', #add whitenoise 'django.contrib.sessions.middleware.SessionMiddleware', ... ] #... STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') ##specify static root Then, modify your wsgi.py file as explained in Johnny's answer: #wsgi.py from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise application = get_wsgi_application() application = DjangoWhiteNoise(application) After that, deploy your changes to your server (with git or whatever you use). Finally, run the collectstatic option from your manage.py on your server. This will copy all files from your static folders into the STATIC_ROOT directory we specified before: $ python manage.py collectstatic You will now see a new folder named staticfiles that contains such elements.

在遵循这些步骤之后,您现在可以运行您的服务器,并且能够在生产模式下看到您的静态文件。

更新:如果你有版本< 4,更新日志表明不再需要声明WSGI_APPLICATION = 'projectName.wsgi。你的settings.py文件中的Application '。

在urls.py中,我添加了这一行:

from django.views.static import serve 

在urlpatterns中添加这两个url:

url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}), 
url(r'^static/(?P<path>.*)$', serve,{'document_root': settings.STATIC_ROOT}), 

当DEBUG=FALSE时,静态文件和媒体文件都可以访问。