Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select default value of <select> element in Django

I have a drop down menu that is created in the following fashion:

<select id="ip_addr">
    {% for host in hosts %}
        <option value="{{ host.ipaddress }}">{{ host.ipaddress }}</option>
    {% endfor %}
</select>

and I don't know how to set the default value. Normally I would just say something like

<option value="0.0.0.0" selected>0.0.0.0</option>

but since I am populating this drop down menu with a loop I don't know how to make sure that the option I want is selected. I'm sure there is a really straight forward way to do this, but I am still pretty new to HTML/JavaScript/Django.

like image 796
DjangoNoob Avatar asked Sep 21 '25 10:09

DjangoNoob


1 Answers

You have 2 options, using Django templates built-in features:

  1. If you want to set the first host as the default select option
  2. If you want to set an specific host as the default select option

Here are the 2 possible solutions:

<select id="ip_addr">
    {% for host in hosts %}
        <option value="{{ host.ipaddress }}" {% if forloop.first %}selected{% endif %}>{{ host.ipaddress }}</option>
    {% endfor %}
</select>
<select id="ip_addr">
    {% for host in hosts %}
        <option value="{{ host.ipaddress }}" {% if host.ipaddress == '0.0.0.0' %}selected{% endif %}>{{ host.ipaddress }}</option>
    {% endfor %}
</select>

Note: foorloop.first is a special template loop variable, that is True during the first iteration of a loop.

like image 179
suselrd Avatar answered Sep 23 '25 00:09

suselrd