Django Form unexpected keyword argument

Question:

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'

Asked By: Rafik Bouloudene

||

Answers:

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.

Answered By: dgw
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.