0

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!

Bubbleboy
  • 71
  • 9
  • possible duplicate of [How to get an ImageField URL within a template?](http://stackoverflow.com/questions/8850535/how-to-get-an-imagefield-url-within-a-template) – rnevius Jun 08 '15 at 15:22
  • Try this [answer](http://stackoverflow.com/a/30626791/3945375) – Gocht Jun 08 '15 at 15:39

2 Answers2

1

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.

Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
1

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/

Aditya Pandhare
  • 501
  • 7
  • 16