【问题标题】:why thumbnail are not displayed in img tag using the values() method in views?为什么使用视图中的 values() 方法在 img 标签中不显示缩略图?
【发布时间】:2021-08-03 15:52:38
【问题描述】:

我有一个包含 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>

请帮忙

【问题讨论】:

  • 因为.values 只返回一个字典,因此您不能在thumbnail 上调用.url,因为它不再是FieldFile
  • 这是使用.values()的(众多)原因之一。

标签: django


【解决方案1】:

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

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

def home(request):
    #                            no .values() &downarrow;
    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 &downarrow;
    ).only('pk', 'slug', 'code', 'area', 'thumbnail')[:8]
    context = {
        'allvilla': allVilla,
        'allproduct': allproduct,
    }
    return render(request, "wooden/home.html", context)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2023-03-20
    • 2019-03-27
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多