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

时间:2019-10-03 17:35:08

标签: django image django-models media django-urls

我正在尝试将发布的图像显示在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连接混乱了。

1 个答案:

答案 0 :(得分: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 %}