How to set deafult value of django form select field in template?
How to set deafult value of django form select field in template?
CodePudding user response:
To set the default value of a Django form select field, you can use the selected
attribute of the <option>
tag in the template. For example, if you have a form field called country
and you want to set the default value to "United States", you can use the following code in the template:
<select name="country">
<option value="United States" selected>United States</option>
<option value="Canada">Canada</option>
<option value="Mexico">Mexico</option>
<!-- more options here -->
</select>
Alternatively, you can use the initial
attribute of the form field to set the default value in the form's __init__
method. For example:
class MyForm(forms.Form):
country = forms.ChoiceField(choices=COUNTRY_CHOICES, initial="United States")
Then in the template, you can simply use the {{ form.country }}
to render the form field. The default value will be automatically set to "United States".
CodePudding user response:
Simply you can do this way:
<select id="ip_addr">
{% for host in hosts %}
<option value="{{ host.ipaddress }}" {% if forloop.first %}selected{% endif %}>{{ host.ipaddress }}</option> #here default value will be first value from for loop
{% endfor %}
</select>
This is the way you can do