Python Django窗体读取动态窗体ChoiceField值

Python Django窗体读取动态窗体ChoiceField值,python,django,django-forms,Python,Django,Django Forms,我有一个Django表单,其中设置了一个动态ChoiceField,其中包含从数据库中提取的值。该表格从登记参加体育比赛的运动员那里获取信息,并按体重等级对他们进行分类。我已经制作了表单以根据需要显示条目,并且我能够读取ChoiceField,但是我似乎无法读取用户选择的单选按钮的值。显示动态表单的代码为: def __init__(self, event, *args, **kwargs): super(EntryForm, self).__init__(*args, **kwargs

我有一个Django表单,其中设置了一个动态ChoiceField,其中包含从数据库中提取的值。该表格从登记参加体育比赛的运动员那里获取信息,并按体重等级对他们进行分类。我已经制作了表单以根据需要显示条目,并且我能够读取ChoiceField,但是我似乎无法读取用户选择的单选按钮的值。显示动态表单的代码为:

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>

上面代码块中的'field'变量引用ChoiceField的标签,但是如何获取用户选择的选项的值呢?在表单的回发数据中,每个选项字段显示为类似于'Junior Men:97'的内容,其中97是用户在表单上选择的体重等级的id。“field”变量返回unicode字符串“Junior Men”,但我只需要数字。我认为选择存储为dict,但这似乎不起作用,因为我无法访问值。

对于提交的数据,您应该使用
form.data
而不是
form.fields
。我假设您正在验证表单-
form.is\u 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
            )
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
            )