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

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

问题描述

项目目录下的Settings.py文件:

Settings.py file in Project directory :

我已经添加了以下内容:

I already added following :

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

-> 在模板中

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

我在项目目录下有一个目录 static.home.js 位于 static 下的 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 应用程序以提供用于本地开发的静态文件的步骤.

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

STATIC_ROOT 默认为 None,因此您必须在设置中指定.确保您的 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')

Second 还指定您的 STATIC_URL 变量,因为它也默认为无.以下应该就足够了.这将用于设置 urlpattern.

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 中指定的所有文件复制到/static/(STATIC_ROOT) 目录以供 django 提供服务.

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.

生产中,您希望您的网络服务器/反向代理说 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天全站免登陆