首页 > 解决方案 > 为什么使用视图中的 values() 方法在 img 标签中不显示缩略图?

问题描述

我有一个有 10 个字段的模型。但是在模板中我只想返回四个字段('slug', 'code', 'area', 'thumbnail') 。为此,我在 View 中使用了 Values()。但是缩略图没有显示在模板的img标签中,并且照片的src是空的。视图.py:

def home(request):
allVilla = Villa.objects.filter(status='p').values('slug', 'code', 'area', 'thumbnail')[:8]
context = {
    'allvilla': allVilla,
    'allproduct': allproduct,
}
return render(request, "wooden/home.html", context)

home.html(模板):

<div id="slider_villa_home" class="owl-carousel owl-theme box_slider_villa dir_left">
           
            {% for v in allvilla %}
            <div class="item position-relative box_item wow flipInY">
                <div class="position-absolute bg"></div>
                <img class="img_item" src="{{ v.thumbnail.url }}" alt="{{ v.code }}">
                <p class="position-absolute p_item">
                    <b>{{ v.code }}</b>
                    <br>
                    <b>{{ v.area }}</b>
                </p>
                <a class="position-absolute link_item" href="{% url 'wooden:singlevilla' v.slug %}">
                    </a>
            </div>
            {% endfor %}
        </div>

在此处输入图像描述

请帮忙

标签: django

解决方案


如果你使用.values(…)[Django-doc],那么 Django 将返回一个字典集合。因此,这意味着模型的逻辑层(及其字段)不再起作用,因此v.thumbnail.url没有意义,因为v.thumbnail它是一个简单的字符串,因此不再FieldFile具有.url属性。

您最好加载模型对象,并使用这些对象,所以:

def home(request):
    #                            no .values() ↓
    allVilla = Villa.objects.filter(status='p')[:8]
    context = {
        'allvilla': allVilla,
        'allproduct': allproduct,
    }
    return render(request, "wooden/home.html", context)

如果您想最小化带宽以仅返回列的一个子集,您可以使用.only(…)[Django-doc]

def home(request):
    allVilla = Villa.objects.filter(
        status='p'    # using only ↓
    ).only('pk', 'slug', 'code', 'area', 'thumbnail')[:8]
    context = {
        'allvilla': allVilla,
        'allproduct': allproduct,
    }
    return render(request, "wooden/home.html", context)

推荐阅读