【问题标题】:I am having trouble linking Css File to Django Template我在将 Css 文件链接到 Django 模板时遇到问题
【发布时间】:2019-06-26 10:45:00
【问题描述】:

我刚开始学习 django 框架,我尝试添加和使用静态文件来设计具有简单 css 的网页模板(以更改背景),但我的 css 文件似乎没有像背景那样与 html 模板链接不变。

我查找了各种解决方案,似乎我在代码中没有做错任何事情,但它仍然不起作用。请看代码,我可能缺少什么?

这是模板的代码;

{% load staticfiles %}
<link rel="stylesheet" type="text/css" href="music/style.css">


{% if all_albums %}
<h3>My Albums</h3>
<ul>
    {% for album in all_albums %}
    <li><a href="{% url 'music:detail' album.id %}">{{album.album_title}}</a></li>
    {% endfor %}
</ul>

{% else %}
<h3>You don't have any albums</h3>
{% endif %} 

这是css;

body{
    background: white url("images/blackbackground.jpg");
}

我预计背景会改变,但事实并非如此。服务器返回错误消息“未找到:/music/music/style.css [01/Feb/2019 12:15:26] "GET /music/music/style.css HTTP/1.1" 404 2559" 伙计们,我错过了什么?

【问题讨论】:

  • 为什么是 /music/music ?看起来很混乱,你试过href="./style.css"

标签: css django python-3.x django-templates django-staticfiles


【解决方案1】:

要使静态文件在 Django 上工作,您需要准备好几个变量。

首先,在您的settings.py 中,您必须设置静态文件变量。

这里我给你看一个我使用的例子:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'staticfiles')
STATICFILES_DIRS = (
    'static',
    os.path.join(os.path.dirname(BASE_DIR), 'static')
)
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

这意味着您需要在与您的主应用程序相同的文件夹中拥有一个静态文件夹。

例如:

├── apps
│   ├── api
│   ├── blog
│   └── home
├── manage.py
├── media
│   ├── images
│   └── original_images
├── requirements
│   ├── base.txt
│   ├── development.txt
│   └── production.txt
├── src    -----> THIS IS MY MAIN FOLDER
│   ├── __init__.py
│   ├── __pycache__
│   ├── db.sqlite3
│   ├── locale
│   ├── media
│   ├── settings ------> THIS IS MY SETTINGS FOLDER
│   ├── urls.py
│   └── wsgi.py
├── static    ------> THIS IS MY STATIC FOLDER
│   ├── css
│   ├── figures
│   ├── fonts
│   ├── img
├── templates
│   └── base.html
└── utilities

接下来,您需要将其添加到您的主要urls.py

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

# Serve static files with Django. Normally this is for development purposes.
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

之后,最后一部分进入您的模板,您需要加载静态模板标签并使用以下语法:

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

最后,它会呈现如下内容:

<link rel="stylesheet" type="text/css" href="/static/music/style.css">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    相关资源
    最近更新 更多