【发布时间】:2012-07-18 08:38:57
【问题描述】:
所以我使用 jQuery UI 来skin the radio buttons,但我无法让 Django 以必须完成的方式呈现我的表单。
我需要这个结构:
<table>
<tr>
<td><label for="notify_new_friends">Notify when new friends join</label></td>
<td class="radio">
<input type="radio" name="notify_new_friends" id="notify_new_friends_immediately" value="1" checked="checked"/><label for="notify_new_friends_immediately">Immediately</label>
<input type="radio" name="notify_new_friends" id="notify_new_friends_never" value="0"/><label for="notify_new_friends_never">Never</label>
</td>
</tr>
</table>
总结一下,我需要一个类(单选)中的单选按钮,它们有一个input 和一个label for。
当我使用 {{ profile_form.notify_new_friends }} 在模板中呈现表单时,我得到以下信息:
<ul>
<li><label for="id_notify_new_friends_0"><input type="radio" id="id_notify_new_friends_0" value="0" name="notify_new_friends" /> Immediately</label></li>
<li><label for="id_notify_new_friends_1"><input type="radio" id="id_notify_new_friends_1" value="1" name="notify_new_friends" /> Never</label></li>
</ul>
这正是我想要的,除了列表部分。所以我尝试循环遍历它,这给了我不同格式的标签:
{% for item in profile_form.notify_new_friends %}
{{ item }}
{% endfor %}
这给了我:
<label><input type="radio" name="notify_new_friends" value="0" /> Immediately</label>
<label><input type="radio" name="notify_new_friends" value="1" /> Never</label>
所以这里的问题是它停止使用label for 并开始使用label 来包装它。
我也尝试过这样做,但是 label 和 label_tag 不渲染任何东西。
{{ profile_form.notify_new_friends.0 }}
{{ profile_form.notify_new_friends.0.label_tag }}
{{ profile_form.notify_new_friends.0.label }}
那么有谁知道我该如何正确渲染它!?
仅供参考,这是我的 forms.py:
self.fields['notify_new_friends'] = forms.ChoiceField(label='Notify when new friends join', widget=forms.RadioSelect, choices=NOTIFICATION_CHOICES)
【问题讨论】:
-
@AlexanderA.Sosnovskiy 是的,但我错过了
choice_label来获得标签标题,但不幸的是,{{ radio.tag }}没有为我提供 ID,因此我不能这样做label for我需要做的。 -
字段 id 是自动生成的尝试,{{ field.auto_id }}
-
@ArgsKwargs 我可能误解了如何使用它,但不,这并没有给我任何渲染。
标签: django django-forms django-templates