图像不会在Django中加载到模板,但会存储到媒体文件中

问题描述 投票:0回答:1

我正在尝试将发布的图像显示在Listview Blog应用程序上。

Models.py

from django.db import models
class Post(models.Model):
    image = models.ImageField(upload_to='Post_images',null=True)
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    success_url = "post-detail"
    template_name = 'post_form.html'

urls.py

from django.conf.urls.static import static
from django.conf import settings
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

home.html

{% extends "blog/blogbase.html" %}
{% block content %}
    {% for post in posts %}
         {% if Post.image %}
            <img src="{{ post.image.url }}" class="img-responsive">
           {% else %}
           <span class="text-muted">No cover</span>
           {% endif %}
    {% endfor %}

我在所有Post.image未注册的帖子上看到“没有封面打印”。

settings.py

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

我认为这与媒体根目录有关,因为当我上传图像时,它会保存到媒体文件中。我认为html / urls / settings连接混乱了。

django image django-models media django-urls
1个回答
0
投票

您的错误在于模板的以下几行:

{% for post in posts %}
         {% if Post.image %}
            <img src="{{ post.image.url }}" class="img-responsive">
           {% else %}
           <span class="text-muted">No cover</span>
           {% endif %}
    {% endfor %}

在第二行中,您已从for循环中大写了post。它应该是post.image,而不是Post.image

完整的固定代码:

{% extends "blog/blogbase.html" %}
{% block content %}
    {% for post in posts %}
         {% if post.image %}
            <img src="{{ post.image.url }}" class="img-responsive">
           {% else %}
           <span class="text-muted">No cover</span>
           {% endif %}
    {% endfor %}
© www.soinside.com 2019 - 2024. All rights reserved.