Django表单读取动态ChoiceField值
我在Django中设置了一个表单,这个表单有一个动态的选择字段,选项是从数据库中获取的。这个表单是用来收集参加体育比赛的运动员的信息,并根据体重级别进行分类。我已经把表单做得可以显示所需的条目,并且能够读取选择字段的内容,但我就是无法获取用户选择的单选按钮的值。用来显示动态表单的代码是:
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)
这段代码渲染出的表单是:
男子青少年组
- 男子青少年轻量级
- 男子青少年中量级
- 男子青少年重量级
女子青少年组
- 女子青少年轻量级
- 女子青少年中量级
- 女子青少年重量级
在HTML中显示为:
<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'变量指的是选择字段的标签,但我该如何获取用户选择的选项的值呢?在表单的POSTBACK数据中,每个选择字段显示为类似'男子青少年组: 97'的格式,其中97是用户在表单中选择的体重级别的ID。'field'变量返回的是字符串'男子青少年组',但我只想要那个数字。我原以为选项是以字典的形式存储的,但似乎并不奏效,因为我无法访问到这个值。
1 个回答
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
)