如何将媒体目录中的图像显示到模板中? Django的

时间:2019-01-13 18:36:40

标签: python django django-templates

我正在使用Django创建自己的管理面板。 但是,如果我尝试显示从Django管理面板上传的图像,浏览器会告诉我找不到该图像。

我已经将MEDIA_URL和MEDIA_ROOT添加到settings.py中,但是如果我尝试打印此变量,则在模板中看不到任何内容。

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 个答案:

答案 0 :(得分:0)

根据Django关于MEDIA_ROOTmanaging files的文档,METDIA_ROOT应该具有服务器文件系统到媒体文件夹的绝对路径。 “ /”表示Linux文件系统的根目录。下面是配置它的两种正确方法。

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'