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

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

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

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

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


当前回答

实际上,你可以在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())

其他回答

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 '。

从这里我得到了一些帮助,混合了一些答案。这里,我把所有的部分相加。[我这样做是为了初学者的帮助,也是为了我将来的使用]

首先的问题是为什么需要Debug=False ! 我把我的项目放在AWS中,由于内存泄漏,几个小时后连接超时。 一开始我想用芹菜。[当然我只是个初学者] 然后把DEBUG=False从DEBUG=True改为DEBUG=False,正如我们在settings.py中看到的安全警告

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

一旦我这样做,我的静态文件在网页中加载不成功。 然后我到处搜索,首先尝试从这里——insecure命令运行服务器。

python manage.py runserver --insecure

这是成功的,但我不希望我的项目在生产时采用不安全模式。 在我看来,正确的解决方法是以下步骤。

首先,我纠正了settings.py中的静态URL、根目录和目录

STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

然后通过命令收集静态文件

python manage.py collectstatic

现在是第二步,[这里也提供了] 首先在命令行中的项目目录中安装白噪声

pip install whitenoise

然后添加'whitenoise.middleware。在settings.py中中间件列表中的WhiteNoiseMiddleware'。

这应该添加在django.middleware.security下面。SecurityMiddleware'以及所有其他中间件。这样你的中间件列表看起来就像这样:-

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware', #after this line
    'whitenoise.middleware.WhiteNoiseMiddleware', #add it exactlyhere
    'django.contrib.sessions.middleware.SessionMiddleware', #before this
    '...'
]

在你安装的应用程序顶部添加'whitenoise.runserver_nostatic',这样你安装的应用程序列表将看起来像这样

INSTALLED_APPS = [
    'whitenoise.runserver_nostatic',
    'django.contrib.admin',
    'django.contrib.auth',
    '...'
]

完成后,您现在就可以在生产环境中提供静态文件了!![我对我当地的环境也是这样做的]

只要像往常一样使用runserver命令,不需要任何不安全或其他任何东西。

python manage.py runserver

繁荣! !这对我很有用。 哈哈哈。我知道我有点孩子气,但我现在很开心。

感谢所有在这里提供答案并帮助我工作的人。

如果你在开发中使用静态服务视图,你必须有DEBUG = True:

警告 这只在DEBUG为True时有效。 这是因为这种观点过于粗暴 效率低下,而且可能不安全。 这只适用于本地 开发,绝不应该使用 在生产中。

文档:在开发中提供静态文件

更新链接,还有这个

编辑:你可以添加一些url只是为了测试你的404和500模板,只是在你的url中使用通用视图direct_to_template。

from django.views.generic.simple import direct_to_template

urlpatterns = patterns('',
    ('^404testing/$', direct_to_template, {'template': '404.html'})
)

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

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

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可以很好地提供静态文件。