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



跟随Django的Polls Webapp教程。通过我的命令行一直收到404错误,并且显示我的图像图标,但不显示图像本身。

尝试更改路径几次,重置静态迁移,并更改我的静态根。还是没有图像

这是我的style.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">

这是我的一些设置。py

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

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

有人知道吗?

  1. 最好在选择器(锚标记)中添加:link和/或:visited
  2. 在属性background-imageurl值的开头加上正斜杠(/)。
li a:link,
li a:visited {
color: green;
}
body {
background-image: url('/static/images/background.png') no-repeat;
}
  1. imgsrc中移除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)

相关内容

  • 没有找到相关文章

最新更新