【问题标题】:Unable to display ImageField within Django template无法在 Django 模板中显示 ImageField
【发布时间】:2017-05-31 00:01:04
【问题描述】:

我希望你能帮助我完成我的 Django 项目。我可以在基于 slug 名称的文件夹内的 media_cdn 文件夹下上传图像。当我尝试在我的帖子列表和帖子中显示图像时出现问题。

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

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)

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

【问题讨论】:

  • 您检查的是if post.image,然后是post.instance.image.url
  • post.image 解决了我的问题。非常感谢!

标签: python django imagefield django-1.10 media-url


【解决方案1】:

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

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

【讨论】:

  • 嘿 AKS,非常感谢,它解决了我的问题。出于某种原因,我以为我已经尝试过了,但由于某种原因,它第一次没有用。你为我节省了很多时间。祝你有美好的一天!
猜你喜欢
  • 2020-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-25
  • 2014-08-31
  • 1970-01-01
  • 2012-05-15
相关资源
最近更新 更多