CSS背景图片未在Django框架中显示

hwamh0ep  于 2023-04-08  发布在  Go
关注(0)|答案(1)|浏览(224)

按照Django中的Polls Webapp教程。通过我的命令行不断收到404错误,显示我的图像图标,但不是图像本身。
尝试改变路径几次,重置静态迁移,并改变我的静态根。仍然没有图像。
这是我的风格. css

li a {
    color: green;
}

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

这里是我的index.html

{% 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 %}

{% load static %}

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

<img src="{% static 'static/images/background.png' %}" alt="My Image">

这里是我的一些settings.py

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

有人有主意吗?

az31mfrm

az31mfrm1#

1.最好将:link和/或:visited添加到选择器(锚标记)
1.在属性background-imageurl值的开头添加正斜杠(/)。

li a:link,
li a:visited {
    color: green;
}

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

1.从img src中删除static/

{% load static %}

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

<img src="{% static 'images/background.png' %}" alt="My Image">

{% 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 %}

1.删除STATIC_URL中的正斜杠(/)并在settings.py中添加STATICFILES_DIRS
settings.py

STATIC_URL = 'static/'

MEDIA_URL = '/images/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
]

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

1.确保已更新urls.py中的urlpatterns
<project_name>/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 = [
    path('admin/', admin.site.urls),
    ...
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

相关问题