How can I display images from media directory into template? Django

Viewed 3982

I'm using Django to create my own administration panel. But if I try to display the images uploaded from the Django Admin Panel, the browser tell me that not found the image.

I've added the MEDIA_URL and the MEDIA_ROOT to the settings.py but if I get and try to print this variable I don't see anything in the template.

settings.py
MEDIA_ROOT = '/'
MEDIA_URL = '/media/'
models.py
class HomePhoto(models.Model):
    image_path = models.ImageField(upload_to='media/home/photos/', null=False, blank=False)
    home = models.ForeignKey(Home, on_delete=models.CASCADE, related_name='home_photos', null=False, blank=True)
views.py
...
def get_context_data(self, **kwargs):
       context = super(HomeDetailView, self).get_context_data()
       context['title'] = context['home'].address
       context['home_photos'] = home_models.HomePhoto.objects.filter(home=context['home'].pk)
       return context
template.html
{% load static %}
{% get_media_prefix as MEDIA_URL %}
{% block content %}
...
{% for photo in home_photos %}
    <div class="{% if forloop.first %}active{% endif %} item" data-slide-number="0">
        <img src="{{ MEDIA_URL }}{{ photo.image_path }}">
    </div>
{% endfor %}
...
{% endblock %}


1 Answers

Per Django's document about MEDIA_ROOT and managing files, METDIA_ROOT should has absolute path of server file system to the media folder. The '/' means root of Linux file system. Below are the two right ways to configure it.

settings.py
# In case media folder is in your project folder
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# In case media folder is at different location, likes /var/www/media
MEDIA_ROOT = '/var/www/media'
Related