[英]Unable to display ImageField within Django template
I hope you can help me withmy Django project. 希望您能为我的Django项目提供帮助。 I am able to upload an images under a media_cdn folder, inside a folder based on the name of the slug.
我可以根据子弹的名称在文件夹中的media_cdn文件夹下上传图像。 The problem occurs when I try to display the image inside my post list and post.
当我尝试在我的帖子列表和帖子中显示图像时,会出现问题。
Can you please have a look at my code and offer a solution. 您能否看一下我的代码并提供解决方案。 I spent hours trying to get it to work.
我花了几个小时试图使其工作。 Please help.
请帮忙。
settings.py 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 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 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 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 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)
I don't know what else to try to call that image from the folder. 我不知道还有什么尝试从该文件夹中调用该图像的。 Any advice would be greatly appreciated.
任何建议将不胜感激。 Thank you!
谢谢!
Use post.image.url
instead of post.instance.image.url
. 使用
post.image.url
而不是post.instance.image.url
。 Check the documentation . 检查文档 。
ImageField
inherits all the attributes of the FileField
which includes url
. ImageField
继承的所有属性FileField
包括url
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.