8

How to display images from model in templates?

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

For example:

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

3 Answers 3

14

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

Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

If it is well documented there, it is not clear to beginners how to do so. Currently I get the correct url, but no image
5

You are missing in your root/project urls.py the following code.

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 

Your code server will return module not found errors also until you import in the urls.py also. And for some reason, it has to be the root urls.py, even if you have individual urls.py files for separate applications

from django.conf import settings from django.conf.urls.static import static 

Comments

0

in the product case it becomes difficult to find the fault. this reduces it a bit

if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) else: urlpatterns += staticfiles_urlpatterns() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.