Austin Bailey
Austin Bailey

Reputation: 55

Django dynamic ModelChoiceField field

Trying to pass in a variable to help with the queryset that ModelChoiceField requires. Getting error TypeError: __init__() takes at least 2 arguments (1 given) and I'm not sure why. See code below.

forms.py

class uploadForm(forms.Form):

    def __init__(self, trainer, *args, **kwargs):
        super(uploadForm, self).__init__(trainer, *args, **kwargs)
        self.fields["client"] = forms.ModelChoiceField(
                      queryset=Trainee.objects.filter(trainer=trainer),
                      widget=forms.Select(attrs={'class': 'signup-form-input'})
                   )

views.py

uploadForm = uploadForm(trainer)

Upvotes: 0

Views: 574

Answers (1)

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58271

You are getting this exception because following code line is wrong:

super(uploadForm, self).__init__(trainer, *args, **kwargs)

In init method. It should be just

super(uploadForm, self).__init__(*args, **kwargs)

as in super class's constructor trainer is not an argument.

Anyways, the way you are doing is wrong! you should implement your form class as below:

forms.py:

class UploadForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(UploadForm, self).__init__(*args, **kwargs)
        self.fields["client"] = forms.ModelChoiceField(
            queryset=Trainee.objects.filter(trainer=kwargs['trainer']),
            widget=forms.Select(
                attrs={
                    'class': 'signup-form-input'
                }
            ))

views.py:

uploadform = UploadForm(trainer=trainer)

One more note: If trainer is not a field in your form then popup trainer before to call super class constructor as:

class UploadForm(forms.Form):
    def __init__(self, *args, **kwargs):
        trainer = kwargs.pop('trainer', None)  
        super(UploadForm, self).__init__(*args, **kwargs)
        self.fields["client"] = forms.ModelChoiceField(
            queryset=Trainee.objects.filter(trainer=trainer),
            widget=forms.Select(
                attrs={
                    'class': 'signup-form-input'
                }
            ))

views.py is as I given in my answer.

Upvotes: 2

Related Questions