This field is required error in the "Form" class

32 views Asked by At

I have a problem in my form. When I print the error it says "The field is required". can anyone tell me what I am missing.

here is my code

forms.py:

from django import forms

class LoginAuth(forms.Form):
    Email= forms.EmailField()
    Password= forms.CharField(max_length=300)

views.py:

from django.shortcuts import render
from .forms import LoginAuth
def login(request):
    if request.method=="POST":
        form = LoginAuth(request.POST)
        if form.is_valid():
            Email= form.cleaned_data['email']
            Password= form.cleaned_data['pass']
            request.session['user']= Email
            request.session.set_expiry(2)
            print("The form is validated")
        else:
            print(form.errors)
    return render(request, "login.html")

login.html:

{% extends 'base.html' %}
{% block content %}
      <form method="post">
       {% csrf_token %}
        <input type="email" name="email" placeholder="Enter Email"> <br>
        <input type="password" name="pass" placeholder="Enter Password"> <br> <br>
        <input type="submit">
      </form>
{% endblock %}
1

There are 1 answers

1
willeM_ Van Onsem On

The names are Email and Passowrd in your form, not email and pass. You might want to rename these in the Django form to:

class LoginAuth(forms.Form):
    email = forms.EmailField()
    password = forms.CharField(max_length=300)

then in the form use:

{% extends 'base.html' %}
{% block content %}
      <form method="post">
       {% csrf_token %}
        <input type="email" name="email" placeholder="Enter Email"> <br>
        <input type="password" name="password" placeholder="Enter Password"> <br> <br>
        <input type="submit">
      </form>
{% endblock %}

and in the view then use password instead of pass: naming a variable pass is not possible in Python, or at least not without some meta-programming:

from django.shortcuts import render

from .forms import LoginAuth


def login(request):
    if request.method == 'POST':
        form = LoginAuth(request.POST, request.FILES)
        if form.is_valid():
            request.session['user'] = email = form.cleaned_data['email']
            password = form.cleaned_data['password']
            request.session.set_expiry(2)
            print('The form is validated')
        else:
            print(form.errors)
    else:
        form = LoginAuth()
    return render(request, 'login.html', {'form': form})