djangoformspostdjango-forms

__init__() got multiple values for argument trying to override forms.Form


I'm trying to override my form to show a select with my data, my problem is when I try to send the form I get this error init() got multiple values for argument.

form.py

class ChangeMemberForm(forms.Form):
    coordinator = forms.ModelChoiceField(queryset=None,label="Pesquisadores", widget=forms.Select(attrs={'class':'form-control'}))
    def __init__(self,ubc, *args,**kwargs):
        super(ChangeMemberForm, self).__init__(*args,**kwargs)
        ubc = Ubc.objects.get(id=ubc)
        self.fields['coordinator'].queryset = ubc.researchers.all()

view.py

def change_coordinator(request, pk):
    template_name =  'ubc/addmember.html'
    ubc = Ubc.objects.get(pk=pk)
    if request.method == "POST":
        form = ChangeMemberForm(request.POST, ubc=ubc.id)
        if form.is_valid():
            print(form.cleaned_data)
        return redirect('accounts:account_detail', pk=request.user.id)
    form = ChangeMemberForm(ubc=ubc.id)
    context = {
        'form': form,
    }
    return render(request, template_name, context)

Solution

  • The order in which you defined the parameters is:

    def __init__(self, ubc, *args, **kwargs):

    whereas you make a call to the __init__ with:

    form = ChangeMemberForm(request.POST, ubc=ubc.id)

    So you called it with an unnamed first parameter, whereas the first parameter is ubc. So as a result, the __init__ function received two values for the ubc parameter: request.POST, and ubc.id, and of course that does not make sense.

    So you should replace it with:

    form = ChangeMemberForm(ubc.id, request.POST)

    So here that means that the first parameter (ubc.id) is redirected to the ubc parameter, and the second (request.POST) is the first parameter of the *args, which is a parameter of the super().__init__ call.