django form validation using "raise forms.ValidationError()"

36 views Asked by At

I'm using a CustomLoginForm for login. In that form, I have created function level validation in forms.py file using forms.ValidationError(). But forms.ValidationError() not even works. I don't know what is the reason. But i'm using django messages, it pop up the messages. please help me why the form validation function not works

forms.py

class CustomLoginForm(forms.Form):


    email = forms.EmailField(
        label='Email',
        max_length=254,
        widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': 'Enter your email'}),
    )
    password = forms.CharField(
        label='Password',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Enter your password'}),
    )
    
    def clean(self):
        cleaned_data = super().clean()
        email = cleaned_data.get('email')
        password = cleaned_data.get('password')
        if email and password:
            user = authenticate(email=email, password=password)
            if user is None:
                raise forms.ValidationError("Invalid email or password. Please try again.")

        return cleaned_data

views.py

def login(request):
    if request.method == "POST":
        form = CustomLoginForm(request.POST)
        if form.is_valid():
            user_email = request.POST.get("email")
            user_password = request.POST.get("password")
            user = authenticate(request, email = user_email, password=user_password)
            if user is not None:
                auth_login(request, user)
                messages.info(request, f"you are now logged in {user_email}")
                return redirect("home")
            else:
                messages.error(request, "invalid email or password or user not exist")
        else:
            messages.error(request, "invalid email or password or user not exist")
    form = CustomLoginForm()
    context = {
        "login_form" : form
    }
    return render(request=request, template_name="account/login.html", context=context)

login.html

{% load static %}
{% load crispy_forms_tags %}
{% block content %}

<!--Login-->
<div class="container py-5">
  <h1>Login</h1>
  <form method="POST" action="{% url 'account:login' %}">
    {% csrf_token %}
    {{ login_form|crispy }}
    <button class="btn btn-primary" type="submit">Login</button>
  </form>
  {% if messages %}
  <ul class="messages">
    {% for message in messages %}
    <li {% if message.tags %} class="{{ message.tags }}" {% endif %}>{{ message }}</li>
    {% endfor %}
  </ul>
  {% endif %}
  <p class="text-center">Don't have an account? <a href="/register">Create an account</a>.</p>
</div>


{% endblock %}```




what is the error in that code? please find it
0

There are 0 answers