Django error: got multiple values for keyword argument

前端 未结 3 1535
你的背包
你的背包 2020-12-31 00:51

I get the following error when instantiating a Django form with a the constructor overriden:

__init__() got multiple values for keyword argument \'collection         


        
3条回答
  •  礼貌的吻别
    2020-12-31 01:24

    Daniel Roseman's solution is to handle a mixture of *args and **kwargs better, but gruszczy's explanation is the correct one:

    You have defined CreateCollectionForm.__init__ with this signature:

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

    And you are then calling it like this:

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

    self is assigned implicitly during the call. After that, Python sees only one positional argument: request.POST, which is assigned as collection_type, the first parameter. Then, the keyword arguments are processed, and when Python sees another keyword argument names collection_type, then it has to throw a TypeError.

    Daniel's solution is a good one, by removing all named parameters, it is much easier to handle things like this, and to pass them up through super() to higher-level constructors. Alternately, you need to make the post dictionary the first formal parameter to your __init__ method, and pass it up to the superclass.

提交回复
热议问题