0

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})

2 Answers 2

1

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/

4
  • Tried your suggestion. But still facing the same issue. No errors in the browser. Dec 26, 2020 at 17:02
  • @ArghyaBhattacharya i updated my answer, let me know if it works.
    – cizario
    Dec 26, 2020 at 17:13
  • @cizaro Added this snippet in the template. Still no show of error. I am using Django 3.1.4 if that matters. Dec 26, 2020 at 18:56
  • The 2nd Update worked. Now its working. Thanks :) Dec 27, 2020 at 6:45
0

Try adding the form error(s) like this:

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

        else:
            print("end")
            return f_N

and also make sure the cleaned firstName is always returned, because with youe current code, it won't be returned for some paths. So to cover this issue, just add a return f_N outside all the ifs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.