Django静态文件CSS不与模板链接

问题描述

正如标题中所述,静态文件某种程度上没有加载到我的模板中。我曾尝试过研究类似的StackOverflow问题,但找不到解决方案。我尝试使用浏览器的开发工具对其进行调试。

我尝试从那里打开CSS文件,但这只会导致我遇到此错误。这使我得出一个结论,即Django在静态文件夹中似乎找不到base.css。我已经完成manage.py collectstatic,所以应该没有问题。谢谢!

Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/static/static/base.css
'static\base.css' Could not be found

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False,and Django will display a standard 404 page.

settings.py

# Static files (CSS,JavaScript,Images)
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR,'static/')

模板

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}">

编辑:从{% static 'static/base.css' %}还原为{% static 'css/base.css' %}

解决方法

首先,您必须更正设置。py:

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

然后,可以说,您将 css文件存储在 static / base.css 中 现在,写{% static 'base.css' %},因为django默认情况下会在应用程序中查找您的静态文件,因此您不必包括静态路径。