簡體   English   中英

如何使用自定義模板標簽在Django模板中顯示圖像對象? (包括編碼)

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

我有以下代碼無法顯示對象圖像。 但是可以正常顯示圖像。

我的模特

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

模板標簽編碼

from django import template
register = template.Library()
from ----.models import ---

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

模板編碼

{% 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 %}

該代碼在列表中輸出所有變量信息,例如標題和正文,但是不顯示相關的圖像。 我已經嘗試過對此代碼進行多種變體而沒有成功。 這很奇怪,因為當以下列方式從圖像文件夾中調用圖像時

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

一切正常。 當其模型圖像被調用時,會出現問題。 非常感謝您解決此問題的任何幫助

這與自定義模板標記無關。 如果查看呈現頁面的源,則會看到{{ object.image }}沒有輸出圖像的URL。 您需要使用{{ object.image.url }}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM