Django表单__init __()获得了关键字参数的多个值

fh_*_*ash 25 django-forms

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

TypeError
__init__() got multiple values for keyword argument 'vUserProfile'
Run Code Online (Sandbox Code Playgroud)

我需要传递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()
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*man 43

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

formPessoa = ClienteForm(request.POST, instance=cliente, vUserProfile=profile)
Run Code Online (Sandbox Code Playgroud)

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

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

def __init__(self, *args, **kwargs):
    vUserProfile = kwargs.pop('vUserProfile', None)
Run Code Online (Sandbox Code Playgroud)


Cha*_*iam 32

谷歌到这里的其他人的帮助:错误来自init从位置参数和默认参数中获取参数.丹尼尔罗斯曼的问题准确无误.

这可以是:

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

    class C():
      def __init__(self, arg): ...
    
    x = C(1, arg=2)   # you passed arg twice!  
    
    Run Code Online (Sandbox Code Playgroud)
  2. 你忘了把它self作为第一个参数:

    class C():
       def __init__(arg):  ...
    
    x = C(arg=1)   # but a position argument (for self) is automatically 
                   # added by __new__()!
    
    Run Code Online (Sandbox Code Playgroud)