form missing 1 required positional argument: 'request'

Viewed 1457

i have used same code for forms in previous apps but this time it doesnt seem to work, migrations have been done and i have been at this for a day and cant find a good solution of why this form isnt working.

def gst_form(request):
    if request.method == 'POST':
        form = gst_form(request.POST)

        if form.is_valid():
            form.save()
            return redirect("/")

        else:
            return HttpResponse("Details Invalid")  


    else:
        form = gst_form()
        
    context= {'form':form}

    return render(request, 'main/form.html', context)
1 Answers

It looks like you have given both your view and your form gst_form as name. This thus means that when you call gst_form in your view, you make a recursive call to the view function, you thus do not construct a form.

An easy way to solve this is to rename your form, for example to GstForm:

class GstForm(forms.ModelForm):
    # …

then there is no longer a name clash:

from ….forms import GstForm

# …

def gst_form(request):
    if request.method == 'POST':
        form = GstForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/')
    else:
        form = GstForm()
    context= { 'form': form }
    return render(request, 'main/form.html', context)

Furthermore this is also compliant with the PEP-0008 style guidelines:

Class names should normally use the CapWords convention.

Related