我正在处理如何在Django中制作自定义表单,现在我仍然坚持提交步骤。
当我按提交时,我收到__init__() got multiple values for keyword argument 'networkList'
。
我的forms.py
:
class SimpleDeploy(forms.Form):
def __init__(self, networkList, policiesList, applicationList, *args, **kwargs):
super(SimpleDeploy, self).__init__(*args, **kwargs)
if networkList and policiesList and applicationList:
self.fields['Network Partition ID:'] = forms.ChoiceField(choices=networkList)
self.fields['Application Policy ID:'] = forms.ChoiceField(choices=policiesList)
self.fields['Application ID:'] = forms.ChoiceField(choices=applicationList)
else:
self.fields['Network Partition ID:'] = forms.ChoiceField(choices='No network partitions found')
self.fields['Application Policy ID'] = forms.ChoiceField(choices='No application policies found')
self.fields['Application ID:'] = forms.ChoiceField(choices='No applications found')
在我的views.py
上,该方法如下:
def simpleDeploy(request):
netList = getDetailsNetworkPartitions(request)
polList = getDetailsApplicationPolicies(request)
appList = getDetailsApplications(request)
if request.method == 'POST':
form = SimpleDeploy(request.POST, networkList=None, policiesList=None, applicationList=None)
if form.is_valid():
network = form.cleaned_data['Network Partition ID:']
policy = form.cleaned_data['Application Policy ID:']
application = form.cleaned_data['Application ID:']
##### more things
else:
simpleForm = SimpleDeploy(networkList=netList, policiesList=polList, applicationList=appList)
else:
simpleForm = SimpleDeploy(networkList=netList, policiesList=polList, applicationList=appList)
return render(request, 'apacheStratos/simpleDeploy.html', {'form': simpleForm})
追溯错误:
Traceback:
File "/usr/local/lib/python2.7/dist-packages/Django-1.8.12-py2.7.egg/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/iago/Escritorio/tfm/website/apacheStratos/views.py" in simpleDeploy
60. form = SimpleDeploy(request.POST, networkList=None, policiesList=None, applicationList=None)
Exception Type: TypeError at /stratos/simpleDeploy
Exception Value: __init__() got multiple values for keyword argument 'networkList'
查看文档,我读到POST请求它始终是第一个参数(request.Post
),在init方法上我认为它与self
对应,而且在其他答案中我看到了有时,data=params
有效,但在我的情况下,我收到错误:need more than 1 value to unpack
<{1}}
回溯:
if form.is_valid():
那么,这是我的错误?谢谢和问候。
答案 0 :(得分:1)
您已定义表单init,以便第一个位置参数为networkList
;因此,当您执行form = SimpleDeploy(request.POST, networkList=None...)
时,位置arg和关键字arg都会使用相同的名称,这是不允许的。
根本不要改变签名;从kwargs获得额外的值。
def __init__(self, *args, **kwargs):
networkList = kwargs.pop('networkList', None)
policiesList = kwargs.pop('policiesList', None)
applicationList = kwargs.pop('applicationList', None)
super(...)
或者,由于您只需要表单中的那些值,您可以考虑将请求传递给此方法并直接在那里获取这些值;相同的语法将适用。