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 %}
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With