如何解决显示图片的“未找到”问题?

时间:2019-04-14 20:31:00

标签: django imagefield detailview

我正在准备网站的博客组件,它是在项目的应用程序内部创建的。除了没有显示图像外,似乎没有任何问题。

在运行时,一切正常,但是仅显示图像“ alt”而不是图像。我在该项目的其他页面中有没有问题的图像。

关于终端的报告: “未找到:/article/static/images/growth_EWAl68g.png [14 / Apr / 2019 17:44:38]“获取/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 /,但地址开头还有一个额外的单词(文章)。

1 个答案:

答案 0 :(得分:1)

只需添加即可解决此问题

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

访问项目的urls.py和

MEDIA_URL ='/ media /' 在settings.py中。