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!
You just need to do:
User uploaded files go to your
MEDIA_ROOT
+ theupload_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)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.