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

Image won't load to template in Django, but is stored to Media file

我正在尝试让张贴的图像显示在 Listview 博客应用程序上。

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 %}

我在所有帖子上看到 "No cover printed",表明 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 连接有问题。

您的错误在模板中的这些行中:

{% 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 %}