图像不显示在网页上(Django)

时间:2018-02-18 11:37:00

标签: python django python-3.x

问题在于,使用Bootstrap 3,从图像中创建了“Carousel”,然后在 Views 中编写了一个循环,将所有带有路径的图像添加到字典中,然后通过循环,输出 HTML视图中的所有图像。

HTML

<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
    <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
    <li data-target="#myCarousel" data-slide-to="1"></li>
    <li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner">
    {% for picture in picture_list %}
    <div class="item active"><img src="{{ picture }}" style="width:100%;">
    </div>
    {% endfor %}
</div>
<!-- Left and right controls -->
<a class="left carousel-control" href="#myCarousel" data-slide="prev">
    <span class="glyphicon glyphicon-chevron-left"></span>
    <span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right"></span>
    <span class="sr-only">Next</span>
</a>

视图

def recipes_list(request):
    recipes = Recipe.objects.filter(created_date__lte=timezone.now()).order_by('created_date')
    pictures = os.listdir(os.path.join(settings.STATIC_PATH, 'images/carousel'))
    picture_list = []
    for picture in pictures:
        path = str(os.path.join(settings.STATIC_PATH, 'images\carousel').replace('\\', '/'))
        picture_list.append('%s/%s' % (path, picture))
    return render(request, 'Recipes/recipes_list.html', {'recipes': recipes, 'sub_form': sub_form, 'picture_list': picture_list})

在浏览器中

<img src="C:/Users/%username%/PycharmProjects/Django/CookBook/Recipes/static/images/carousel/FRIED SAGE1.jpg" style="width:100%;">

1 个答案:

答案 0 :(得分:2)

Django有builtins for handling static files(以及他们的路径)。让它做下功夫。

设置

STATIC_URL = '/static/'
STATIC_PATH = # some path

查看

def recipes_list(request):
    recipes = Recipe.objects.filter(created_date__lte=timezone.now()
                           ).order_by('created_date')
    pictures = os.listdir(os.path.join(settings.STATIC_PATH, 'images/carousel'))
    picture_list = ['images/carousel/%s' % picture
                    for picture in pictures]
    return render(request, 'Recipes/recipes_list.html', {'recipes': recipes, 'sub_form': sub_form, 'picture_list': picture_list})

<强>模板

{% load static %}
...
<div class="carousel-inner">
    {% for picture in picture_list %}
        <div class="item active">
            <img src="{% static picture %}" style="width:100%;">
        </div>
    {% endfor %}
</div>
...