代码之家  ›  专栏  ›  技术社区  ›  Marcus Whybrow

Django错误:为关键字参数获取多个值

  •  21
  • Marcus Whybrow  · 技术社区  · 15 年前

    __init__() got multiple values for keyword argument 'collection_type'
    

    这个 __init__() 函数(如下所示)与本文完全相同,但具有 # code

    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
    )
    

    编辑:这是构造函数的完整代码

    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'
    
    3 回复  |  直到 15 年前
        1
  •  43
  •   Daniel Roseman    15 年前

    你正在通过考试 collection_type collection_type=collection_type 在对表单构造函数的调用中。因此Python将其包含在 kwargs dictionary-但由于您在该函数的定义中将其声明为位置参数,因此它会尝试传递它两次,从而导致错误。

    user=None, parent=None 之前 这个 *args 字典,因为它们已经是夸尔格了,并且args必须总是在夸尔格之前。解决方法是删除集合类型、用户和父项的显式定义,并从函数中的kwargs中提取它们:

    def __init__(self, *args, **kwargs):
        collection_type = kwargs.pop('collection_type', None)
        user = kwargs.pop('user', None)
        parent = kwargs.pop('parent', None)
    
        2
  •  9
  •   gruszczy    15 年前

    In [8]: class A:
       ...:     def __init__(self, a, *args):
       ...:         print a, args
       ...:         
       ...:         
    
    In [9]: A(None, a=None)
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    
    /home/gruszczy/Programy/logbuilder/<ipython console> in <module>()
    
    TypeError: __init__() got multiple values for keyword argument 'a'
    

    将request.POST移动到调用中的其他位置,但请记住,命名参数位于那些参数之后,而不是。

        3
  •  7
  •   Ian Clelland    15 年前

    Daniel Roseman的解决方案是处理 *args **kwargs

    你已经定义了 CreateCollectionForm.__init__ 签名如下:

    def __init__(self, collection_type, user=None, parent=None, *args, **kwargs)
    

    form = CreateCollectionForm(
        request.POST, 
        collection_type=collection_type, 
        parent=parent, 
        user=request.user
    )
    

    self collection_type 另一个 ,则必须抛出一个TypeError。

    super() 给更高层次的建设者。或者,您需要将post dictionary作为 __init__ 方法,并将其传递给超类。