【问题标题】:Django Polls App: Background Image Not LoadingDjango Polls App:背景图像未加载
【发布时间】:2021-03-31 19:19:01
【问题描述】:

我正在学习 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 %}

【问题讨论】:

    标签: python html css django


    【解决方案1】:

    这应该可以解决问题

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

    【讨论】:

    • 这对我不起作用...我还将示例中的文本颜色从绿色更新为蓝色,以确认文件本身正在加载(有效)。我试过这个,还尝试为我的网址添加完整路径。为什么我的背景仍然是白色的?
    【解决方案2】:

    您的背景图片未呈现,因为您为背景图片提供了相对路径。 要么提供绝对路径,要么使用静态模板标签。

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

    【讨论】:

    • 这对我不起作用...我还将示例中的文本颜色从绿色更新为蓝色,以确认文件本身正在加载(有效)。我试过这个,还尝试为我的网址添加完整路径。为什么我的背景仍然显示为白色?
    • 使用 background-image 属性而不是背景。并切换 no-repeat: 可能有效的属性。
    【解决方案3】:

    尝试将此添加到您的 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/')
    

    【讨论】:

      【解决方案4】:

      试试这个:

      background-image: url("C:\Users\xxx\Python\Django\mysite\polls\static\polls\style.css") no-repeat; 
      

      【讨论】:

        猜你喜欢
        • 2014-02-17
        • 2018-02-04
        • 2019-04-26
        • 2017-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-19
        相关资源
        最近更新 更多