Django轮询应用程序:未加载背景图像

2024-09-25 16:22:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Django并开发出第一个测试民意测验应用程序,但在背景图像方面遇到了问题。绿色文本可以工作,但是添加背景图像没有任何作用(背景只是白色)。你知道为什么它不能正常工作吗

背景图像C:\Users\xxx\Python\Django\mysite\polls\static\polls\images\sample123.jpg

样式CSS:C:\Users\xxx\Python\Django\mysite\polls\static\polls\Style.CSS

li a {
    color: blue;
}

body {
        background: url('C:\Users\xxx\Python\Django\mysite\polls\static\polls\images\sample123.jpg');
        background-repeat: no-repeat;
         }

索引HTML:C:\Users\xxxx\Python\Django\mysite\polls\templates\polls

{% load static %}

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

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

Tags: django图像staticliuserscsspollsxxx
3条回答

这应该能奏效

body {
        background: url('/static/images/sample123.jpg');
        background-repeat: no-repeat;
         }

尝试将其添加到polls/urls.py文件中

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
    #....
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #with out this, the images will not be displayed

这在你的polls/settings.py文件中

STATIC_URL = '/static/'
MEDIA_URL = '/static/images/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images/')

未渲染背景图像,因为您为背景图像提供了相对路径。 提供绝对路径或使用静态模板标记

body {
    background: white url({%static 'polls\images\sample123.jpg'%}) no-repeat;
}

相关问题 更多 >