【问题标题】:Jinja for loop wont populate select dropdownJinja for 循环不会填充选择下拉列表
【发布时间】:2016-06-15 13:19:22
【问题描述】:

我有一个 django 项目,我正在尝试使用optgroup 标签填充选择下拉列表,然后在这些标签下填充项目列表。

所以在我的模板中我有 2 个变量,buildingslocations 然后在我的模板中,我迭代所有位置并创建一个optgroup 标签,然后在该标签下我得到所有与location 相关的buildings,但由于某种原因,我的选择从不包含带有我的位置的optgroup 标签

#view.py
    buildings = TBuildings.objects.order_by('ixLocation')
    locations = TLocations.objects.all()

#dropdown.html
<div class="dropdown">
        <!-- test to see if it actually works and it does -- >
        {% for location in locations %}
            <optgroup label="{{ location.asLocation }}">
            </optgroup>
        {% endfor %}

    <!-- this doesn't -->
    <select class="selectpicker" data-width="100%" data-live-search="true" style="border-radius: 0px;">
        {% for location in locations %}
            <optgroup label="test">
            </optgroup>
        {% endfor %}
    </select>
</div>

第一个 for 循环只是为了看看它是否会创建 optgroup 并且确实会创建,但在我的选择中它不会

编辑 我在意识到它不起作用之前尝试使用的代码:

<div class="dropdown">
    <select class="selectpicker" data-width="100%" data-live-search="true" style="border-radius: 0px;">
        {% for location in locations %}
            <optgroup label="{{ location.asLocation }}">
                {% for building in buildings %}
                    {% if building.ixLocation == location.ixLocation %}
                        <option>#{{building.iBuildingNum}} - {{building.asBuildingName}}</option>
                    {% endif %}
                {% endfor %}
            </optgroup>
        {% endfor %}
    </select>
</div>

【问题讨论】:

  • 你的select标签错误
  • 怎么回事?当我手动添加标签时它可以工作

标签: html django jinja2 bootstrap-select


【解决方案1】:

我太傻了。

{% if building.ixLocation == location.ixLocation %}

应该是

{% if building.ixLocation.ixLocation == location.ixLocation %}

因为 building.ixLocation 生成外键字段的名称,所以我的optgroup 标签下的列表是空的,而select 中没有显示任何内容

【讨论】:

    猜你喜欢
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 2013-07-29
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多