Search code examples
htmldjangojinja2bootstrap-select

Jinja for loop wont populate select dropdown


I have a django project where I am trying to populate a select drop down with optgroup tags then under those tags the list of items.

So in my template I have 2 variables, buildings and locations then in my template I iterate all the locations and create an optgroup tag then under that I get all the related buildings to that location but for some reason my select never contains an optgroup tag with my location

#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>

the first for loop was just to see if it would create the optgroup and it does, but inside my select it doesn't

EDIT code i tried to use before realizing it doesn't work:

<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>

Solution

  • stupid of me.

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

    should be

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

    since building.ixLocation produces the foreign key fields' name so my list under my optgroup tag is empty which in turn doesn't display anything in the select