fakeMake
fakeMake

Reputation: 778

Function Based View returns multiple values for a forms kwargs

I have a function based view returns an TypeError on passing a kwarg to a form

TypeError: __init__() got multiple values for argument 'school'

This is the form

class StudentForm(forms.ModelForm):
    def __init__(self, school,*args, **kwargs):
        super(StudentForm, self).__init__(*args, **kwargs)
        self.fields['school'] = forms.ModelChoiceField(
            queryset=Student.objects.filter(school=school))
    class Meta:
        model = Student
        fields = ('name','student_id','batch','depart','semester')
        widgets = {
            'school':forms.TextInput(attrs={'type':'hidden'}),
        }

And the view.

def add_student(request):
    if request.method == 'POST':
        s_form = StudentForm(request.POST,school = request.user.school)
        if s_form.is_valid():
            s_form.save(commit=True)
            return redirect('add_student')
    else:
        s_form = StudentForm()
    return render(request, 'libman/add_student.html', {'s_form': s_form})

Where this have been done???

Upvotes: 1

Views: 57

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477318

Because the first parameter of your init method is school:

def __init__(self, school, *args, **kwargs)

It means that if you make a call with:

StudentForm(request.POST, school=request.user.school)

then both the request.POST and the request.user.school will be seen as values for the school parameter, which makes no sense.

I would advice to rewrite the order of your __init__ method parameters to:

class StudentForm(forms.ModelForm):
    school = forms.ModelChoiceField(queryset=Student.objects.none())

    def __init__(self,*args, school, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['school'].queryset = Student.objects.filter(
            school=school)
        )

Then the request.POST will passed to the super() constructor and thus to the data=… parameter of the ModelForm.

Upvotes: 1

Related Questions