【问题标题】:Django form __init__() got multiple values for keyword argumentDjango 表单 __init__() 为关键字参数获取多个值
【发布时间】:2012-12-28 15:12:31
【问题描述】:

您好,我正在尝试使用修改后的__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()

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

【问题讨论】:

    标签: django-forms


    【解决方案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()
    

    【讨论】:

      【解决方案2】:

      在 Google 到这里的其他人的帮助下:错误来自 init 从位置参数和默认参数中提取参数。丹尼尔·罗斯曼 (Daniel Roseman) 提出的问题是准确的。

      这可以是:

      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__()!
        

      【讨论】:

        【解决方案3】:

        您更改了表单__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)
        

        【讨论】:

        • 非常感谢!现在工作正常.. 我保持签名是默认的.. 并使用您的提示...
        • 我现在有其他问题.. 我怎样才能将此代码传递给一个 inlineformset_factory ?
        • 很好的解决方案,谢谢!有没有人认为有办法在没有 kwargs 把戏的情况下达到同样的效果? Imo 它使 init 的用户友好性降低,能够添加显式关键字参数会很棒。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多