29

您好,我正在尝试使用修改后的__init__表单方法,但遇到以下错误:

TypeError
__init__() got multiple values for keyword argument 'vUserProfile'

我需要传递UserProfile给我的表单,才能到达dbname现场,我认为这是一个解决方案(我的表单代码):

class ClienteForm(ModelForm):
class Meta:
    model = Cliente

def __init__(self, vUserProfile, *args, **kwargs):
    super(ClienteForm, self).__init__(*args, **kwargs)
    self.fields["idcidade"].queryset = Cidade.objects.using(vUserProfile.dbname).all()

ClienteForm()在没有 POST 的情况下调用构造函数是成功的,并向我显示正确的形式。但是当提交表单并使用 POST 调用构造函数时,我得到了前面描述的错误。

4

3 回答 3

49

您已更改表单__init__方法的签名,因此这vUserProfile是第一个参数。但在这儿:

formPessoa = ClienteForm(request.POST, instance=cliente, vUserProfile=profile)

您作为第一个参数传递request.POST- 除了这将被解释为vUserProfile. 然后你也尝试vUserProfile作为关键字 arg 传递。

确实,您应该避免更改方法签名,而只需从以下位置获取新数据kwargs

def __init__(self, *args, **kwargs):
    vUserProfile = kwargs.pop('vUserProfile', None)
于 2013-01-14T16:15:07.880 回答
32

为了帮助谷歌到这里的其他人:错误来自init从位置参数和默认参数中提取参数。丹尼尔罗斯曼的问题对于所问的问题是准确的。

这可以是:

  1. 您按位置然后按关键字放置参数:

    class C():
      def __init__(self, arg): ...
    
    x = C(1, arg=2)   # you passed arg twice!  
    
  2. 你忘了把self作为第一个论点:

    class C():
       def __init__(arg):  ...
    
    x = C(arg=1)   # but a position argument (for self) is automatically 
                   # added by __new__()!
    
于 2013-07-26T00:23:42.507 回答
1

我认为ModelForm就是这种情况,但需要检查。对我来说,解决方案是:

def __init__(self, *args, **kwargs):
    self.vUserProfile = kwargs.get('vUserProfile', None)
    del kwargs['vUserProfile']
    super(ClienteForm, self).__init__(*args, **kwargs)
    self.fields["idcidade"].queryset = Cidade.objects.using(self.vUserProfile.dbname).all()
于 2013-12-15T23:53:21.450 回答