我的一个表单是使用ModelMultipleChoiceField,它显示了html上的复选框列表。
class CreateProfileForm(forms.Form):
first_name = forms.CharField(label='First Name', max_length=50)
last_name = forms.CharField(label='Last Name', max_length=50)
topics = forms.ModelMultipleChoiceField(label='Assign Topic(s)',
widget=CheckboxSelectMultiple(),
queryset=None)
def __init__(self, *args, **kwargs):
event = kwargs.pop('event')
super (CreateProfileForm, self).__init__(*args, **kwargs)
self.fields['topics'].queryset = Topic.objects.filter(event=event)
HTML输出
<div id="div_topics">
<label class="fields">
<strong><label for="id_topics_0">Assign Topic(s)</label></strong>
</label>
<ul>
<li><label for="id_topics_0"><div class="checker" id="uniform-id_topics_0"><span><input type="checkbox" name="topics" value="3" id="id_topics_0" style="opacity: 0; "></span></div> Size</label></li>
<li><label for="id_topics_1"><div class="checker" id="uniform-id_topics_1"><span><input type="checkbox" name="topics" value="2" id="id_topics_1" style="opacity: 0; "></span></div> Flavour</label></li>
<li><label for="id_topics_2"><div class="checker" id="uniform-id_topics_2"><span><input type="checkbox" name="topics" value="1" id="id_topics_2" style="opacity: 0; "></span></div> Citrus</label></li>
</ul>
</div>
如何更改id
元素的input type
的值?或者基本上将id_topics_0
等更改为其他内容?
答案 0 :(得分:1)
试试这个
def __init__(self, *args, **kwargs):
event = kwargs.pop('event')
super (CreateProfileForm, self).__init__(*args, **kwargs)
self.fields['topics'].queryset = Topic.objects.filter(event=event)
self.fields['topics'].widget.attrs['class'] = "new_topics_class"
答案 1 :(得分:0)
您可以添加auto_id选项以形成初始方法。但它会改变这种形式的所有ID: https://docs.djangoproject.com/en/1.3/ref/forms/api/#configuring-html-label-tags