[Answered ]-Django: multiple values for keyword argument 'initial'

1đź‘Ť

âś…

The __init__ function signature is incorrect for a ModelForm.

From the Django source for BaseModelForm you can see that the function signature is:

def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=None,
                 empty_permitted=False, instance=None):

So if anyone instantiates your form with an unnamed argument in the first position as Django does, then you’ll end up with this error.

I’d suggest rewriting your __init__ like this:

 def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance')
        _fields = ('username', 'first_name', 'last_name', 'email', 'password')
        _initial = model_to_dict(instance.dragonuser, _fields) \
            if instance is not None else {}
        kwargs['initial'] = _initial
        super(ParentCreationForm, self).__init__(*args, **kwargs)
        self.fields.update(fields_for_model(DragonUser, _fields))

1đź‘Ť

The problem is that Python won’t let you spec a keyword argument for “instance” in the call to your init (as is being done in …/django/contrib/admin/options.py:1085) because the first argument in the call is getting mapped to “instance” due to the order of parameters and then the third parameter is also getting mapped to “instance” because of being spec’d as a keyword argument.

To fix this, remove instance=None from your __init__ signature and instead in the first line of the method do this:

instance = kwargs.get("instance")

Also remove the instance=instance from the super call as instance should be carried in the kwargs now.

👤David K. Hess

Leave a comment