How to display images from a model in Django?

How to display images from a model in templates?

I will display images from the photo catalog (upload_to = 'photos') in my index.html template. How to do it?

For instance:

My models

class Photo(models.Model): nazwa = models.ImageField(upload_to='photos', verbose_name='My Photo') 

My views

 def index(request): img = Photo.objects.all().order_by('-id') return render_to_response("index.html", {"img": img}) 

My URLs

 urlpatterns = patterns('', url(r'^/?$', 'album.views.index'), (r'^static/(.*)$', 'django.views.static.serve', {'document_root': os.path.join(os.path.dirname(__file__), 'static')}), ) 

My template, index.html

 {% for n in img %} ?? {% endfor %} 
+4
source share
1 answer

Everything you need is well described here and here . You need to pass your img to the template and use its url () method.

In the template, you can do something like this:

 {% for n in img %} <img src="{{ n.nazwa.url }}" /> {% endfor %} 

Hope this helps.

+7
source

Source: https://habr.com/ru/post/1398994/


All Articles