Django 表单 __init__() 为关键字参数获取了多个值 [英] Django form __init__() got multiple values for keyword argument

查看:29
本文介绍了Django 表单 __init__() 为关键字参数获取了多个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hello, I'm trying to use a modified __init__ form method, but I am encountering the following error:

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

我需要将 UserProfile 传递给我的表单,以到达 dbname 字段,我认为这是一个解决方案(我的表单代码):

I need to pass UserProfile to my form, to get to dbname field, and I think this is a solution (my form code):

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 调用构造函数时,我得到了前面描述的错误.

Calls to constructor ClienteForm() without POST are successful and show me the correct form. But when the form is submitted and the constructor is called with POST, I get the previously described error.

推荐答案

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

You've changed the signature of the form's __init__ method so that vUserProfile is the first argument. But here:

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

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

you pass request.POST as the first argument - except that this will be interpreted as vUserProfile. And then you also try to pass vUserProfile as a keyword arg.

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

Really, you should avoid changing the method signature, and just get the new data from kwargs:

def __init__(self, *args, **kwargs):
    vUserProfile = kwargs.pop('vUserProfile', None)

这篇关于Django 表单 __init__() 为关键字参数获取了多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆