开发者

How do you display image objects in a Django template using a custom template tag? (coding included)

开发者 https://www.devze.com 2023-01-21 03:43 出处:网络
I have the following code that fails to display object images. But displays normal images fine. My Model

I have the following code that fails to display object images. But displays normal images fine.

My Model

class News(models.Model):
title-----------
image = models.ImageField(upload_to='images')
body------------

Template tag coding

from django import template
register = template.Library()
from ----.models import -开发者_JS百科--

def funct(num):
myobjects = News.objects.all()[:num]
return {'objects': myobjects}
register.inclusion_tag('news/template.html')(funct)

template coding

{% for object in objects %}
<li>{{ object.title }}</li>
<li><img src="{{ MEDIA_URL }}images/{{ object.image }}" alt="image" /></li>
<li>{{ object.body }}</p></li>
{% endfor %}

This code outputs all the variable information such as title and body in a list however it does not display the associated image. I have tried numerous variations on this code with no success. This is strange because when an image is called from the image folder in the following manner

<img src="{{ MEDIA_URL }}images/star.jpg" />

Everything works fine. The problems occur when its a model image being called. Any help fixing this issue is much appreciated


This has nothing to do with the custom template tag. If you looked at the source for the rendered page, you would see that {{ object.image }} does not output the URL for the image. You need to use {{ object.image.url }}

0

精彩评论

暂无评论...
验证码 换一张
取 消