Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display images from model in Django?

Tags:

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 %}
like image 231
user1239743 Avatar asked Feb 29 '12 11:02

user1239743


People also ask

How do I show images in Django?

How you specify the location of an image in Django is in between {% %}. In between these brackets, you specify static 'images\\Python. png', where Python is the image you want to display which is inside of the images directory in the static directory you create for the current app you are in.

How do I store images in Django?

In Django, a default database is automatically created for you. All you have to do is add the tables called models. The upload_to tells Django to store the photo in a directory called pics under the media directory. The list_display list tells Django admin to display its contents in the admin dashboard.

How to give background image in Django?

If you want to make your background-image dynamic you can either . You can add css class either directly in template i.e. Or use a inline css directly in your html tag.


1 Answers

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.

like image 146
Jingo Avatar answered Sep 29 '22 07:09

Jingo