选择默认值< select> Django中的元素 [英] Select default value of <select> element in Django

查看:55
本文介绍了选择默认值< select> 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>

但是由于我用循环填充了此下拉菜单,所以我不知道如何确保选择了我想要的选项.我敢肯定有一种非常简单的方法可以做到这一点,但是对于HTML/JavaScript/Django我还是很陌生.

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.

推荐答案

使用Django模板内置功能,您有2个选择:

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

  1. 如果要将第一台主机设置为默认选择选项
  2. 如果要将特定主机设置为默认选择选项

以下是两种可能的解决方案:

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>

注意:foorloop.first是一个特殊的模板循环变量,在循环的第一次迭代期间为True.

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

这篇关于选择默认值&lt; select&gt; Django中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆