无法从Django的Choicefield表单中检索选定的值

时间:2017-12-26 09:29:08

标签: django django-forms

以下是我的Django表格

class Country(forms.Form):
    name = forms.CharField()
    country = forms.ChoiceField(widget=forms.Select(attrs={'id':'country'}))

以下是将表单发送到HTML页面之前的代码

form = Country()
    choices = [('a', 'India'), ('b', 'United States of America')]
    form.fields['country'].choices = choices
    form.fields['country'].initial = 'b'
    return render(request,"Test.html",{"form":form})

表格在前端正确呈现,并且还设置了初始值。 当用户单击提交按钮时。它抛出异常。

以下是我在用户点击提交按钮

时编写的代码
f = Country(request.POST)
print (f)
print("Country Selected: " + f.cleaned_data['country'])

我在用户提交后打印表单时收到如下表格。

<tr><th><label for="id_name">Name:</label></th><td><input type="text" name="name" value="ggg" id="id_name" required /></td></tr>
<tr><th><label for="country">Country:</label></th><td><ul class="errorlist"><li>Select a valid choice. a is not one of the available choices.</li></ul><select name="country" id="country">
</select></td></tr>

请帮我解决这个问题。 谢谢!

1 个答案:

答案 0 :(得分:1)

您可以在get方法中添加国家/地区选项,但不能在post方法中添加国家/地区选项。当post表单将ab作为invaild选项时。 这是正确的方法:

forms.py

class Country(forms.Form):
    name = forms.CharField()
    country = forms.ChoiceField(widget=forms.Select(attrs={'id':'country'}))

    def __init__(self, *args, **kwargs):
        choices = kwargs.pop('choices', None)
        initial = kwargs.pop('initial', None)
        super(Country, self).__init__(*args, **kwargs)
        self.fields['country'].choices = choices 
        self.fields['country'].initial = initial 

views.py:

kwarg = {
       'choices': [('a', 'India'), ('b', 'United States of America')],
       'initial': 'b',
}
if request.method == "POST":
    f = Country(request.POST, **kwarg)
    if f.is_vaild():
        # cleaned_data is generate after call is_vaild()
        print("Country Selected: " + f.cleaned_data['country'])
    else:
        print(f.errors.as_text())
else:
    form = Country(**kwarg)
return render(request,"Test.html",{"form":form})