gpt4 book ai didi

django - Django错误:关键字参数有多个值

转载 作者:行者123 更新时间:2023-12-03 11:45:30 24 4
gpt4 key购买 nike

在使用重写的构造函数实例化Django表单时,出现以下错误:

__init__() got multiple values for keyword argument 'collection_type'
__init__()函数(如下所示)与此完全相同,但是 # code用我的逻辑替换了。除此之外,我实质上是重写表单的(是ModelForm)构造函数。
def __init__(self, collection_type, user=None, parent=None, *args, **kwargs):
# code
super(self.__class__, self).__init__(*args, **kwargs)

产生错误的调用如下所示:
form = CreateCollectionForm(
request.POST,
collection_type=collection_type,
parent=parent,
user=request.user
)

我看不到错误 pop 的任何原因。

编辑:这是构造函数的完整代码
def __init__(self, collection_type, user=None, parent=None, *args, **kwargs):
self.collection_type = collection_type
if self.collection_type == 'library':
self.user = user
elif self.collection_type == 'bookshelf' or self.collection_type == 'series':
self.parent = parent
else:
raise AssertionError, 'collection_type must be "library", "bookshelf" or "series"'
super(self.__class__, self).__init__(*args, **kwargs)

编辑:Stacktrace
Environment:

Request Method: POST
Request URL: http://localhost:8000/forms/create_bookshelf/hello
Django Version: 1.1.1
Python Version: 2.6.1
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'libraries',
'users',
'books',
'django.contrib.admin',
'googlehooks',
'registration']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')


Traceback:
File "/Library/Python/2.6/site-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.6/site-packages/django/contrib/auth/decorators.py" in __call__
78. return self.view_func(request, *args, **kwargs)
File "/Users/marcus/Sites/marcuswhybrow.net/autolib/libraries/forms.py" in create_collection
13. form = CreateCollectionForm(request.POST, collection_type=collection_type, user=request.user)

Exception Type: TypeError at /forms/create_bookshelf/hello
Exception Value: __init__() got multiple values for keyword argument 'collection_type'

最佳答案

您将collection_type参数作为关键字参数传递,因为您在对表单构造函数的调用中特别说了collection_type=collection_type。因此,Python将其包含在kwargs字典中-但是由于您也已将其声明为该函数定义中的位置参数,因此它尝试将其传递两次,从而导致错误。

但是,您尝试执行的操作将永远无法进行。您不能在user=None, parent=None字典之前使用*args,因为它们已经是kwargs了,而args必须始终在kwargs之前。解决此问题的方法是删除collection_type,user和parent的显式定义,并从函数中的kwargs中提取它们:

def __init__(self, *args, **kwargs):
collection_type = kwargs.pop('collection_type', None)
user = kwargs.pop('user', None)
parent = kwargs.pop('parent', None)

关于django - Django错误:关键字参数有多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1941812/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com