【问题标题】:Not able to retrieve selected values from Django's Choicefield Form无法从 Django 的 Choicefield 表单中检索选定的值
【发布时间】:2017-12-26 09:29:07
【问题描述】:

以下是我的 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>

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

【问题讨论】:

  • 发布异常
  • 异常:'Country' 对象没有属性'cleaned_data'

标签: django django-forms


【解决方案1】:

您在get 方法中添加国家/地区选项,但未在post 方法中添加。当post 表单将ab 视为无效选项。 这是正确的方法:

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})

【讨论】:

  • 感谢您的回复。我需要将视图中的选择作为参数而不是热编码发送。你能帮我在你的代码上进行编辑吗
  • 来自视图的动态选择的新答案已更新!
  • 谢谢!请在您的答案中找到我编辑的代码。在呈现 HTML 页面之前,我在 view.py 中遇到错误说 list object is not callable。你能解决它吗
  • 需要更多信息。
  • 当通过 kwarg 创建 Country 类的实例作为参数时,它抛出了一个异常,说列表对象是不可迭代的。参考我在您的回复中编辑的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-16
  • 1970-01-01
  • 1970-01-01
  • 2012-08-24
  • 2011-10-02
  • 2014-08-22
相关资源
最近更新 更多