如何在Django中显示来自模型的图像? [英] How to display images from model in Django?
本文介绍了如何在Django中显示来自模型的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在模板中显示模型中的图像?
How to display images from model in templates?
我将在模板index.html中显示来自照片目录(upload_to =照片)的图像。
I will display images from photos directory (upload_to='photos') in my template index.html. How to do?
例如:
我的模型
class Photo(models.Model):
nazwa = models.ImageField(upload_to='photos', verbose_name='My Photo')
我的观点
def index(request):
img = Photo.objects.all().order_by('-id')
return render_to_response("index.html", {"img": img})
我的网址
urlpatterns = patterns('',
url(r'^/?$', 'album.views.index'),
(r'^static/(.*)$', 'django.views.static.serve', {'document_root':
os.path.join(os.path.dirname(__file__), 'static')}),
)
我的模板index.html
My template, index.html
{% for n in img %}
??
{% endfor %}
推荐答案
一切此处和此处。您需要将img传递到模板中并使用其url()方法。
Everything you need is well documented here and here. Youll need to pass your img into the template and use its url() method.
在模板中,您可以执行以下操作:
In your template you can do something like this:
{% for n in img %}
<img src="{{ n.nazwa.url }}" />
{% endfor %}
希望这会有所帮助。
这篇关于如何在Django中显示来自模型的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文