django提供静态文件的404错误。如何设置Django服务静态文件? [英] 404 Error for django serving static files. How to setup django to serve static files?

查看:102
本文介绍了django提供静态文件的404错误。如何设置Django服务静态文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Settings.py文件:

Settings.py file in Project directory :

我已经添加了以下内容:

I already added following :

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

$ b模板中的
$ b

->

-> in template

<script src="{% static "validateurl/home.js" %}"></script>

我在项目目录下有一个目录 static 。 home.js在静态下的 validateurl 目录下。

I have a directory static under project directory. home.js is under validateurl directory under static.

在模板html文件中使用以下代码引用JS文件:

Referring JS File using following in template html file :

请告诉我我在这里想念的东西。

Please advise what am I missing here.

以下错误:

推荐答案

以下是配置django应用以为 local 开发提供静态文件的步骤。

Here are the steps to configure your django app to serve static files for local development.

STATIC_ROOT的默认值为无,因此您必须在设置中指定该值。确保您的settings.py中有类似的内容。这会告诉您的网络服务器在哪里找到并提供映射到url的静态文件。

The STATIC_ROOT default is None so you have to specify that in settings. Make sure you have something like this in your settings.py This tells your webserver where to find and serve the static file mapped to a url.

import os
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

第二个也指定您的STATIC_URL变量,因为它也默认为none。以下内容就足够了。

Second also specify your STATIC_URL variable as it also defaults to none. following should suffice. This will be used for setting up the urlpattern.

STATIC_URL = '/static/'

您需要使用url模式,以便您的服务器知道与静态文件对应的url

You need to have a url pattern so your server knows what url corresponds to the static files

from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

指定STATICFILES_DIRS设置中的变量。这样,收集静态管理器便知道在哪里可以找到静态变量并将其放入STATIC_ROOT中。这可以是到不同目录的项目的数组或元组。如果没有其他目录,则可以为空

Specify STATICFILES_DIRS variable in settings. So that the collect static manager knows where to find statics and put them in the STATIC_ROOT. This can be an array or tuple of items to different directories. This can be empty if you have no additional directories

STATICFILES_DIRS =  (os.path.join(BASE_DIR, 'pathtohomejsdirectory/'),)

最后,请确保您运行 python manage.py collectstatic
这会将STATICFILES_DIRS中指定的所有文件复制到django服务的/ static /(STATIC_ROOT)目录中。

Finally, make sure you run python manage.py collectstatic This copies all the files specified in STATICFILES_DIRS over to the /static/ (STATIC_ROOT) directory to be served by django.

制作中,您希望您的Web服务器/反向代理使用nginx或apache来提供文件。请参阅此处django文档这里

On a production, you want your webserver/reverse proxy say nginx or apache to serve the files. See here django documentation here

这篇关于django提供静态文件的404错误。如何设置Django服务静态文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆