为什么浏览器不加载静态文件?

时间:2019-12-22 08:15:24

标签: django django-2.2

settings.py

STATIC_URL = '/static/'
STATICFILES_DIR = [
os.path.join(BASE_DIR, 'static_in_env')
]

STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root')
MEDIA_URL = '/media/'

django.contrib.staticfiles已包含在install_apps中。 base.html中使用的{%从staticfiles%加载static。 仍然出现这些错误:

[22/Dec/2019 13:45:31] "GET / HTTP/1.1" 200 10735
[22/Dec/2019 13:45:32] "GET /static/js/jquery-3.4.1.min.js HTTP/1.1" 404 
1791
[22/Dec/2019 13:45:43] "GET /static/css/bootstrap.min.css HTTP/1.1" 404 
1788
[22/Dec/2019 13:45:43] "GET /static/css/mdb.min.css HTTP/1.1" 404 1770
......

script.html

{% load static from staticfiles %}

<script type="text/javascript" src="{% static 'js/jquery-3.4.1.min.js' 
%}"> 
</script>
<!-- Bootstrap tooltips -->
<script type="text/javascript" src="{% static 'js/popper.min.js' %}"> 
</script>
<!-- Bootstrap core JavaScript -->
<script type="text/javascript" src="{% static 'js/bootstrap.min.js' %}"> 
</script>
<!-- MDB core JavaScript -->
<script type="text/javascript" src="{% static 'js/mdb.min.js' %}"> 
</script>
<!-- Initializations -->
<script type="text/javascript">
// Animations initialization
new WOW().init();

</script>

staticfiles目录包含以下文件和文件夹

static_in_env

 - css
   -bootstrap.css
   -bootstrap.min.css
   -mdb.css
   -mdb.min.css
   -mdb.lite.css
   -mdb.lite.min.css
   -style.css
   -style.min.css
 - font
 - img
 - js
    -bootstrap.js
    -bootstrap.min.js
    -mdb.js
    -mdb.min.js
    -popper.min.js
 - scss

3 个答案:

答案 0 :(得分:1)

在您的project_name/urls.py中,尝试在末尾添加以下内容:

urlpatterns = [
    # your urls...
]

# ↓ add this ↓
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

此外,只需将{% load static %}放入您的script.html,而不是{% load static from staticfiles %}

答案 1 :(得分:0)

在settings.py中添加

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

在base.html

{% load static %}

希望它能在不运行此命令的情况下运行

Python manage.py collectstatic

答案 2 :(得分:0)

如果您正在使用引导,请下载它或使用CDN

UIView

或您可以使用bootstrap提供的入门模板,该模板将包含所有基本的html,css和js文件。链接:https://getbootstrap.com/docs/4.4/getting-started/introduction/ 自定义css链接可以按以下方式链接到文件

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">