在Django项目中连接CSS

0 投票
3 回答
57 浏览
提问于 2025-04-12 14:36

请告诉我错误是什么。在运行了 python manage.py collectstatic 之后,文件生成了,js脚本可以正常工作,但CSS文件没有连接上。

base.html

<!doctype html>
{% load static %}
<html lang="en">
  <head>
   ....
    <!--Custome CSS-->
    <link rel="stylesheet" href="{% static 'static/css/style.css' %}">
    <title>{% block title %} {% endblock %}</title>
  </head>

文件夹:

folder

settings.py

STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / STATIC_URL

我尝试添加文档中的代码:

from django.conf import settings
from django.conf.urls.static import static

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

3 个回答

0

谢谢大家。路径确实是错的,但还是需要被删除:

STATIC_ROOT = BASE_DIR / STATIC_URL

设置中发生了什么:

STATIC_URL = 'static/'

STATICFILES_DIRS = [
    BASE_DIR / "static"
]

#STATIC_ROOT = BASE_DIR / STATIC_URL
0

如果你的CSS文件放在静态文件夹里,那么你需要这样写:

<link rel="stylesheet" href="{% static 'style.css' %}">

如果在静态文件夹里还有一个像css这样的子文件夹,那么你就需要这样写:

<link rel="stylesheet" href="{% static 'css/style.css' %}">
0

请使用下面的内容。

<link rel="stylesheet" href="{% static 'css/style.css' %}">

撰写回答