记住Django中的单选按钮选择

时间:2011-04-21 07:28:58

标签: django

不使用javascript,是否有更好的方法来记住用户的单选按钮选择?我觉得我有一种非常天真(?)的方式吗?

我怎样才能重新写这个以使它更干?提交时,usersegment parem会在同一页面上返回。

{% if usersegment == "non-paying" %}
<input type="radio" name="usersegment" value="non-paying" checked="yes"/> Non-paying Users <br />
<input type="radio" name="usersegment" value="paying" /> Paying Users <br />
<input type="radio" name="usersegment" value="all" /> All Users<br />
{% endif %}

{% if usersegment == "paying" %}
<input type="radio" name="usersegment" value="non-paying" /> Non-paying Users <br />
<input type="radio" name="usersegment" value="paying" checked="yes"/> Paying Users <br />
<input type="radio" name="usersegment" value="all" /> All Users<br />
{% endif %}

{% if usersegment == "all" or not usersegment %}
<input type="radio" name="usersegment" value="non-paying" checked="yes"/> Non-paying Users <br />
<input type="radio" name="usersegment" value="paying" /> Paying Users <br />
<input type="radio" name="usersegment" value="all" checked="yes"/> All Users<br />
{% endif %} 

1 个答案:

答案 0 :(得分:6)

这个怎么样:

<input type="radio" name="usersegment" value="non-paying" {% if usersegment == "non-paying" %}checked="checked"{% endif %}/> Non-paying Users <br />
<input type="radio" name="usersegment" value="paying" {% if usersegment == "paying" %}checked="checked"{% endif %}/> Paying Users <br />
<input type="radio" name="usersegment" value="all" {% if usersegment == "all" or not usersegment %}checked="checked"{% endif %}/> All Users<br />

另外,请考虑使用django forms。像那些琐碎的问题在那里以非常优雅的方式解决,你甚至不需要考虑它。