无法从Django的Choicefield表单检索所选值
以下是我的Django表格无法从Django的Choicefield表单检索所选值,django,django-forms,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')
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})
表单在前端正确呈现,初始值也已设置。
当用户单击提交按钮时。它正在抛出异常
下面是我在用户单击submit按钮时编写的代码
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>
请帮我做这个。
谢谢 在get方法中添加国家选项,但在post方法中不添加国家选项。何时post表单将a或b作为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})
发布exceptionException:“Country”对象没有“cleaned_data”属性,感谢您的回复。我需要将视图中的选项作为参数发送,而不是热编码。你能帮我在你的代码上编辑一下吗?更新了新的答案,从视图中动态选择!谢谢请查找我在您的答案中编辑的代码。在呈现HTML页面之前,我遇到一个错误,即列表对象不能在view.py中调用。你能修复它吗?except的更多信息是必需的。当kwarg将实例创建到Country类作为参数时,它抛出了一个异常,表示list对象不可iterable。请参考我在您的回复中编辑的代码