跟随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')
有人知道吗?
- 最好在选择器(锚标记)中添加:link和/或:visited
- 在属性
background-image
的url
值的开头加上正斜杠(/)。
li a:link,
li a:visited {
color: green;
}
body {
background-image: url('/static/images/background.png') no-repeat;
}
- 从
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 %}
- 从
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')
- 确保你在
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)