问题
In the beginning everything worked perfectly fine, but now I have a problem where my static files doesn't load. I think this is a very weird problem since I didn't really touch anything that could've had an influence on the problem when it happened. Everything else is working fine, I just can't get the static files for some reason. I sometimes get a 200 http response trying to get the static files like so:
[20/Aug/2020 16:12:51] "GET /order/checkout/ HTTP/1.1" 200 2029
[20/Aug/2020 16:12:51] "GET /static/my_pizza_place/js/client.js HTTP/1.1" 200 2194
[20/Aug/2020 16:12:51] "GET /static/css/master.css HTTP/1.1" 200 80
[20/Aug/2020 16:12:51] "GET /static/css/global.css HTTP/1.1" 200 530
But it's still not applying the styling to my html code. I usually just get a 304 http response on my client.js file though. I feel like I have tried almost everything at this point, so I hope you guys can help me figuring out what the problem is.
My files:
- SETTINGS.PY
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
- BASE.HTML
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
...
<link rel="stylesheet" href="{% static 'css/master.css' %}">
<link rel="stylesheet" href="{% static 'css/global.css' %}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="..." crossorigin="anonymous">
<script src="{% static 'my_pizza_place/js/client.js' %}" defer></script>
</head>
<body>
<div class="container mycontent">
{% block checkout %}
{% endblock %}
</div>
</body>
</html>
- INDEX.HTML
{% extends 'base.html' %}
{% block content %}
...
{% endblock %}
- URLS.PY - IN PROJECT FOLDER
urlpatterns = [
path('admin/', admin.site.urls),
path('',views.HomePage.as_view(),name="home"),
path('customer/',include('customer.urls', namespace='customer')),
path('customer/',include('django.contrib.auth.urls')),
path('order/',include('orders.urls',namespace='order'))
]
- VIEWS.PY
class HomePage(TemplateView):
template_name = 'index.html'
DIRECTORY STRUCTURE
- Project
- app_name
- project_name
- static
- css
- global.css
- master.css
- my_pizza_place
- js
- client.js
- templates
- base.html
If you need any more information please just ask. Thanks in advance
回答1:
Your problem is simply that you should add {% load static %} in each file. You don't have to necessarily link the css files in each .html file, but in each file you should load the static files. I have faced this problem before and I am sure this will solve it for you, be sure to add the {% load static %} before the {%block content %} tag. If you need further explanation, comment below.
来源:https://stackoverflow.com/questions/63509019/static-files-doesnt-load-anymore-django