django - 如何解决显示图像的“未找到”问题?
问题描述
我正在准备网站的博客组件,它是在项目的应用程序中创建的。除了不显示图像之外,似乎没有问题。
运行时,一切正常,但只显示图像“alt”而不是图像。我在该项目的其他页面中有没有问题的图像。
终端上有报告:“未找到:/article/static/images/growth_EWAl68g.png [14/Apr/2019 17:44:38]”GET /article/static/images/growth_EWAl68g.png HTTP/1.1”404 6164" 如您所见,Django 使用虚假地址(静态文件夹位于项目的根目录)来访问图像。
class BlogArticle(models.Model):
title = models.CharField(max_length=150)
headline = models.CharField(max_length=300)
body = models.TextField()
post_image = models.ImageField(upload_to ="static/images")
date = models.DateTimeField(auto_now_add=True)
author = models.CharField(max_length=100)
def __str__(self):
return self.title
class ArticleListView(ListView):
model = BlogArticle
template_name = 'article_list.html'
urlpatterns = [
path('', views.HomeView, name= 'home'),
path('article/', views.ArticleListView.as_view(), name='article_list'),
path('article/<int:pk>/', views.ArticleDetailView.as_view(), name='article_detail'),
.
.
.]
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),
path('accounts/', include('allauth.urls')),
path('contactus', include('sendemail.urls')),
path('', include('myapp.urls')),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
{% block content %}
<div <div class="container mt-5 bg-light">
{% for article in object_list %}
<div class="form-row">
<div class="form-group col-sm-9 ">
<div class="post-entry">
<h5 > <a href = "{% url 'article_detail' article.pk %}" > {{ article.title }}</a></h5>
<div>
<p class="font-weight-bold"> {{article.headline }} </p>
</div>
<div>
<span class="text-muted">by {{article.author }} | {{ article.date|date:"M d, Y"}}</span>
</div>
</div>
</div>
<div class="form-group col-sm-3 ">
<div class="thumbnail">
<img src="{{article.post_image}}" width=100 height=100 class="rounded" alt="{{article.title}}">
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock content %}
.
DEBUG = True
ALLOWED_HOSTS = []
.
.
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),]
.
.
看不懂这个条件,看来django应该去static/images/但是地址开头多了一个词(文章)。
解决方案
这个问题通过添加简单地解决了
urlpatterns +=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
到项目的 urls.py 和
MEDIA_URL = '/media/' 在 settings.py 中。
推荐阅读
- apache-kafka - KSQL 如何从已经包含一些消息的主题中读取(使用 msgs)数据
- ios - 在 Swift 中以 50 行/秒的速度存储大量数据
- javascript - 如何更改字段属性:只读和更改按钮后保存
- xamarin.android - 在xamarin android中安装后如何知道应用程序是否第一次打开
- javascript - 如何使用扩展语法在嵌套对象上创建或替换编辑?
- scala - 使用 spark-submit 跟踪和记录/调试从 scala 二进制文件启动的纱线应用程序
- automated-tests - 空手道框架的 JSON 报告
- javascript - 我的多项目轮播在调整屏幕大小时折叠(引导)
- build - vsts中msbuild的路径是什么
- angular - Angular 5 字符串常量外化