Display images on Django Template Site

794 views Asked by At

I read a lot about including image files, but i still don't get it :(

my models.py

class Movie(models.Model):
    image_url = models.URLField(max_length=1024, blank=True, null=True)
    image_file = models.ImageField(upload_to='poster/', blank=True)

my index.html

{% load staticfiles %}
<img src="{% static "{{movie.image_file}}" %}" />

The pictures are saved on harddisk /myapp/poster

Thanks for helping.

Got it!

<img src="
    {% if movie.image_file %}
        {{ movie.image_file.url }}
    {% else %}
        another-image.jpg
    {% endif %}"
/>

urls.py

+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

settings.py

added MEDIA_URL

Thanks a lot!

2

There are 2 answers

9
Brandon Taylor On BEST ANSWER

You just need to do:

<img src="{{ movie.image_file.url }}" />

User uploaded files go to your MEDIA_ROOT + the upload_to parameter in your model field, which is typically a different location that static files are served from when using the {% static %} template tag.

Since your field allows for blank=True you can use a conditional to show a different image, or no image at all: (spaces added to avoid wrapping)

<img src="
    {% if movie.image %}
        {{ movie.image_file.url }}
    {% else %}
        another-image.jpg
    {% endif %}"
/>

alternatively, you could add a model property that does the same thing, or you can just wrap the entire image tag in the if statement to hide it if the field is empty.

0
Aditya Pandhare On

Set MEDIA_ROOT and add following lines at the end of your urls.py +static(settings.STATIC_URL,document_root=settings.STATIC_ROOT)+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Example:

urlpatterns = patterns('',
    url(r'^$', views.index, name='Index'),
    url(r'^admin/', include(admin.site.urls)),
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

In img src write {{MODEL_NAME.FIELD_NAME.url}}

This is only for development. Refer https://docs.djangoproject.com/en/1.8/howto/static-files/