Error "TypeError: FirstForm() missing 1 required positional argument: 'request'"

Daribian

Good day!

When working views.py constantly you get this kind of error:

TypeError: FirstForm() missing 1 required positional argument: 'request'

Views.py

def FirstForm(request):
if request.method == 'GET':
    form = FirstForm()
else:
    form = FirstForm(request.POST)
    if form.is_valid():
        name = form.cleaned_data['name']
        email = form.cleaned_data['email']
        date = form.cleaned_data['date']
        number = form.cleaned_data['number']
        try:
            send_mail(email, (name, date, number), settings.EMAIL_HOST_USER, ['[email protected]'])
        except BadHeaderError:
            return HttpResponse('Invalid header found.')
        return redirect('success')
return render(request, 'index.html', {'form': form})

def successView(request):
    return HttpResponse('Success!')

Сan you tell me what the problem is?

Willem Van Onsem

Your view has the same name as the form, hence if you call FirstForm, you will call the view, not the form.

Therefore it is better to name the view, different, for example first_view:

def first_view(request):
    if request.method == 'GET':
        form = FirstForm()
    else:
        form = FirstForm(request.POST, request.FILES)
        if form.is_valid():
            name = form.cleaned_data['name']
            email = form.cleaned_data['email']
            date = form.cleaned_data['date']
            number = form.cleaned_data['number']
            try:
                send_mail(email, (name, date, number), settings.EMAIL_HOST_USER, ['[email protected]'])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            return redirect('success')
    return render(request, 'index.html', {'form': form})

Note: according to PEP-8, you should write the functions in snake_case, not camelCase, so success_view, instead of successView.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related