我设置了一个Django表单,其中包含一个动态ChoiceField,其值从数据库中提取。该表格从运动员登记参加体育比赛的信息中获取信息,并按重量等级对其进行分类。我已经使表单根据需要显示条目,我能够读取ChoiceField,但我似乎无法读取用户选择的RadioButton的值。显示动态表单的代码是:
def __init__(self, event, *args, **kwargs):
super(EntryForm, self).__init__(*args, **kwargs)
weight_groups = ClassGroup.objects.all()
weight_classes = RegistrationClassOrder.objects.filter(event = event).order_by('class_order')
for single_class in weight_classes.all():
self.fields['%s' % single_class.competition_class.class_group.group_name] = forms.ChoiceField(choices=[ (o.id, o.class_name) for o in weight_class.competition_class.class_group.classes_in_group.all()], widget=forms.RadioSelect(), label=weight_class.competition_class.class_group.group_name, required=False)
这会将表单呈现为:
少年男子
少年女性
:
<th>
<label for="id_Junior Men_0">Junior Men</label>
</th>
<td><ul>
<li><label for="id_Junior Men_0"><input id="id_Junior Men_0" name="Junior Men" type="radio" value="97" /> Junior Men's Lightweight</label></li>
<li><label for="id_Junior Men_1"><input id="id_Junior Men_1" name="Junior Men" type="radio" value="98" /> Junior Men's Middleweight</label></li>
<li><label for="id_Junior Men_2"><input id="id_Junior Men_2" name="Junior Men" type="radio" value="99" /> Junior Men's Heavyweight</label></li>
</ul></td>
在处理表单的视图中,我使用以下代码:
for field in form.fields:
if WeightClassGroup.objects.filter(group_name=field).count() > 0: #checking to see if the field's name matches a weight class in the database
newentry = Entry(
athlete = athlete,
event = event,
athlete_class = Classes.objects.get(id=field)
)
上面代码块中的'field'变量是指ChoiceField的标签,但是如何获取用户选择的选项的值 ?在表单的POSTBACK数据中,每个ChoiceField显示为'Junior Men:97',其中97是用户在表单上选择的权重类的id。 'field'变量返回unicode字符串'Junior Men',但我只想要这个数字。我认为选择存储为dict,但这似乎不起作用,因为我无法访问该值。
答案 0 :(得分:0)
您应该使用form.cleaned_data
而不是form.fields
来提交数据。我假设您在使用数据前验证表单form.is_valid()
。
这样你的观点就像:
for fname, value in form.cleaned_data.iteritems():
if WeightClassGroup.objects.filter(group_name=fname).count() > 0: #checking to see if the field's name matches a weight class in the database
newentry = Entry(
athlete = athlete,
event = event,
athlete_class = Classes.objects.get(id=value) #use value for id in submitted data
)