无法在模板中显示使用ImageField上传的图像

时间:2019-08-24 09:09:12

标签: python django

因此,我有一个博客应用程序,当我想使用ImageField文件浏览器将封面图像添加到文章中时,我的图像名称在PyCharm中显示为红色,而未在模板中显示。但是,当我检查其HTML代码源时,图像路径是正确的。这是我的代码:

articles.html

<a href="/"><img src="{{ article.image.url }}" class="image"/></a>

settings.py


STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_URL = '/media/'

models.py

class Article(models.Model):
    title = models.CharField(max_length=100)
    description = models.CharField(max_length=200)
    content = HTMLField()
    # image = models.CharField(max_length=2000)
    image = models.ImageField(upload_to='media')
    category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True)
    post_date = models.DateTimeField(auto_now_add=True)
    slug = models.SlugField(unique=True, null=True, editable=False)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        self.slug = latin_slugify(self.title)
        super(Article, self).save(*args, **kwargs)

urls.py

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

1 个答案:

答案 0 :(得分:0)

正是由于DEBUG = False,将其值更改为True才解决了问题。