user1239743
user1239743

Reputation: 93

How to display images from model in Django?

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

Upvotes: 8

Views: 21404

Answers (3)

ZeQ
ZeQ

Reputation: 71

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()

Upvotes: 0

Sha Lom
Sha Lom

Reputation: 59

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

Upvotes: 5

Jingo
Jingo

Reputation: 3240

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.

Upvotes: 14

Related Questions