Home > other >  Django Form unexpected keyword argument
Django Form unexpected keyword argument

Time:01-22

i have a form which contains a choiceField and i need to populate it from a view, so i'm trying to use the kwargs inside the init function like this :

class SelectionFournisseur(forms.Form):
    def __init__(self,*args, **kwargs):
        super(SelectionFournisseur, self).__init__(*args, **kwargs)
        self.fields['Fournisseur'].choices = kwargs.pop("choixF",None)
    
    Fournisseur = forms.ChoiceField(choices = ())

my view :

formF = SelectionFournisseur(choixF=choices)

but i get the error BaseForm.__init__() got an unexpected keyword argument 'choixF'

CodePudding user response:

You have to store the extra argument before calling super and afterwards use the stored argument

class SelectionFournisseur(forms.Form):
    def __init__(self, *args, **kwargs):
        self._choixF = kwargs.pop('choixF', None)
        super().__init__(*args, **kwargs)
        self.fields['Fournisseur'].choices = self._choixF

Now your extra argument does not interfere with the super().__init__ call.

  • Related