【问题标题】:Image won't load to template in Django, but is stored to Media file图像不会加载到 Django 中的模板,而是存储到媒体文件中
【发布时间】:2019-10-03 17:35:08
【问题描述】:

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

模型.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 连接搞砸了。

【问题讨论】:

  • 在您的 HTML 中,将 {% if Post.image %} 更改为 {% if post.image %}post != Post.
  • 您应该使用post.image 而不是Post.image

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


【解决方案1】:

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

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

【讨论】:

  • 谢谢!它在模型中大写,但不是在这里。图像仍然无法正确显示,但至少我得到了有图像的指示。
  • 没问题。如果这样可以解决此问题,请点击我的答案左侧的复选标记。
  • 在模板中,post 不是模型,而是模型的实例。你是人类的一个实例。模型是物种的模板。
猜你喜欢
  • 2012-06-02
  • 1970-01-01
  • 1970-01-01
  • 2019-05-21
  • 2013-04-18
  • 2013-12-23
  • 2018-10-15
  • 1970-01-01
  • 2021-05-18
相关资源
最近更新 更多