无法在 Django 模板中显示 ImageField

Unable to display ImageField within Django template

我希望你能帮助我完成我的 Django 项目。我可以在 media_cdn 文件夹下上传图像,该文件夹位于基于 slug 名称的文件夹内。当我尝试在 post 列表和 post.

中显示图像时出现问题

能否请您看看我的代码并提供解决方案。我花了几个小时试图让它工作。请帮忙。

settings.py

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

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn/')

models.py

def upload_location(instance, filename):
    return "%s/%s" %(instance.slug, filename)

class Post(models.Model):
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique=True)
    image = models.ImageField(upload_to=upload_location,
            null=True, 
            blank=True,
            width_field="width_field", 
            height_field="height_field")
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)
    body = models.TextField()
    date = models.DateTimeField()
    updated = models.DateTimeField(auto_now=True)

postlist.html

{% block content %}
    {% for post in posts %}
        <div class="container w3-card-4">
        {% if post.image %}
            <img src="{{ post.instance.image.url }}">
        {% endif %}
...

post.html

{% block content %}
<div class="row">
    <div class="container w3-card-4">
        {% if instance.image %}
        <img src= "{{ instance.image.url }}" class="img-responsive">
        {% endif %}
...

url.py

from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('personal.urls')),
    url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),
]

if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

我不知道还有什么可以尝试从文件夹中调用该图像。任何建议将不胜感激。谢谢!

使用 post.image.url 而不是 post.instance.image.url。检查 documentation.

ImageField 继承了 FileField 的所有属性,其中包括 url.