djangoformsdjango-formsvalidationerror

Django form not returning validation error even when it is supposed to?


In the console I can see that it has printed the "Less" string, that means the control is going inside the "if len(f_N) < 2", but then the validation error is not printed. Please help me out on whats wrong with the code.

####My forms.py file:####

from django import forms
from django.core.exceptions import ValidationError

class UserRegistrationForm(forms.Form):
    GENDER=[('male','MALE'),('female','FEMALE')]  
    firstName= forms.CharField()
    lastName= forms.CharField()
    email= forms.CharField(widget=forms.EmailInput,required=False,initial='Youremail@xmail.com')
    address=forms.CharField(widget=forms.Textarea)
    gender=forms.CharField(widget=forms.Select(choices=GENDER))
    password=forms.CharField(widget=forms.PasswordInput)
    ssn=forms.IntegerField()

    def clean_firstName(self):
        f_N=self.cleaned_data['firstName']
        print(f_N)
        if len(f_N)>15:
            raise forms.ValidationError('Max length allowed is 15 characters')
        if len(f_N) < 2:
            print(len(f_N))
            print("less")
            raise forms.ValidationError('Min length showuld be 2 characters')

        else:
            print("end")
            return f_N

#######My html file######

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>User Registration</title>
</head>

<body>
  <h1> User Registration</h1>

  <table>
  <form method="post">
    
    {% csrf_token %}

    {{form.as_table}}
    </table>
    <button type="submit" name="button">Submit</button>
  </form>


</body>

</html>

##########My views.py file##########

from django.shortcuts import render
from .forms import UserRegistrationForm
from .models import User
# Create your views here.
def UserRegistrationView(request):
    form=UserRegistrationForm()
    if request.method=='POST':
        form_1=UserRegistrationForm(request.POST)
        if form_1.is_valid() :    
            #print(form_1.cleaned_data)
            form_1=form_1.cleaned_data 
            print(request.POST)
            print(form_1)
            user_1=User()
            user_1.firstName=form_1['firstName']
            user_1.lastName = form_1['lastName']
            user_1.email = form_1['email']
            user_1.save()
        
    return render(request,'formsDemo/userRegistration.html',{'form':form})

Solution

  • refer to this topic https://docs.djangoproject.com/en/3.1/ref/forms/validation/#cleaning-a-specific-field-attribute

    in your forms.py you imported ValidationError the right way with from django.core.exceptions import ValidationError but then you are raising it the wrong way in your function clean_firstName(), it should be

        raise ValidationError('..')
    

    and NOT

        raise forms.ValidationError('..')
    

    Update

    in your views.py, since you have form_1=UserRegistrationForm(request.POST) then you should pass form_1 to the context in render statement and NOT form. Any way you can do things the proper way (and you won't need the second form_1 anymore):

    def UserRegistrationView(request):
    
        form=UserRegistrationForm()
    
        if request.method=='POST':
    
            form=UserRegistrationForm(request.POST)
    
            if form.is_valid():
                user = form.save(commit=False)
                user.save()
    
                # Note: 
                # 1. if it happens 'form.is_valide()' returns false, then you'll
                # get the errors in 'form.errors' bag.
                # 2. you don't need to import User Model since you are using 'formMdel'
    
                # maybe you need to redirect to home page if you successfully saved
                # the new user .. display a flash message .. 
    
        return render(request,'formsDemo/userRegistration.html',{'form':form})
    

    refer to this tuto https://tutorial.djangogirls.org/en/django_forms/