首页 > 解决方案 > Django 无法从 css 添加背景图片

问题描述

我按照django官方文档设置了静态路径。文档

我删除了隔离的 css 文件并将样式放入我的 HTML 文件中。似乎 HTML 文件成功获取了样式。

在我的 setting.py 中,我确认这 STATIC_URL = '/static/'是默认设置。

我在我的应用程序文件夹下创建了一个名为 static 的新文件夹,用于呈现此 HTML 页面,并在我的项目下创建相同的文件夹,我将它们中的内容保持不变,因为我不确定哪个是真正的“静态”它识别的路径。

图片只是没有出现。

我在这里尝试了Add background image in css的解决方案,但它根本没有。

我试过:

header.masthead {
  position: relative;
  background-color: #343a40;
  background: url("../static/img/main.jpg") no-repeat center center;
  background-size: cover;
  padding-top: 8rem;
  padding-bottom: 8rem;
}

它不起作用

请帮我。谢谢!

编辑,这是我的文件结构:我摆脱了孤立的 CSS 文件并将所有内容复制到 HTML 文件中。现在它有了 CSS 样式,但仍然无法获取图像。

MyProject
├── static
│   └──img
│       └── img_I_want_to_use_as_background.jpg
├── app
│   └── static
│   │     └──img
│   │         └── img_I_want_to_use_as_background.jpg
│   └── views.py (renders the HTML file)
│   └── other files and dirs under the app

标签: htmlcssdjango

解决方案


您应该在您的应用程序中创建一个静态文件夹。

应用程序看起来像这样: App_name > Static > App_name > css > landing-page.min.css

在这种情况下,模板应该这样说:

{% load static %}

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

https://docs.djangoproject.com/en/3.1/intro/tutorial06/#customize-your-app-s-look-and-feel

它在哪里说: Put the following code in that stylesheet (polls/static/polls/style.css)

{% load static %}

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

推荐阅读