Python Django:将ChoiceField选项传递到表单';s`\uuu init\uu()`作为位置参数会导致AttributeError
我正在尝试将一个参数从views.py传递到forms.py,以使用Python Django:将ChoiceField选项传递到表单';s`\uuu init\uu()`作为位置参数会导致AttributeError,python,django,django-forms,Python,Django,Django Forms,我正在尝试将一个参数从views.py传递到forms.py,以使用CheckboxSelectMultiple小部件创建ChoiceField,但渲染失败 异常类型:AttributeError异常值:“列表”对象没有 属性“get” 请你看看下面,看看我做错了什么:( 提前谢谢你的帮助 forms.py: class TestSubmitForm(forms.Form): tests = forms.ChoiceField() def __init__(self,*args
CheckboxSelectMultiple
小部件创建ChoiceField
,但渲染失败
异常类型:AttributeError异常值:“列表”对象没有
属性“get”
请你看看下面,看看我做错了什么:(
提前谢谢你的帮助
forms.py:
class TestSubmitForm(forms.Form):
tests = forms.ChoiceField()
def __init__(self,*args,**kwargs):
self.testList = args[0]
super(TestSubmitForm,self).__init__(*args,**kwargs)
self.fields['tests'].widget = forms.CheckboxSelectMultiple()
self.fields['tests'].choices = self.testList
views.py
def index(request):
tc_obj_form = [("","1"),("","2"),("",3")]
tests = TestSubmitForm(tc_obj_form)
return render(request, 'index.html',{'tests':tests})
index.html
<form action="." method="POST">
<table >
{% csrf_token %}
{{ tests }}
</table>
<input type="submit" value="Submit"/>
</form>
更改表单的
\uuuu init\uuuu()
,如下所示:
def __init__(self, testList, args,**kwargs):
self.testList = testList
super(TestSubmitForm,self).__init__(*args,**kwargs) # testList not in args!
# ...
问题是forms.Form
(您通过super(…)
调用)的\uuuu init\uuuu()
需要一个类似dict
的对象作为其第一个位置参数。通常,如果提供了该参数,将是类似request.POST
的QueryDict
实例
def __init__(self, testList, args,**kwargs):
self.testList = testList
super(TestSubmitForm,self).__init__(*args,**kwargs) # testList not in args!
# ...