Django form validation problem in clean method

58 Views Asked by At

I'm new to the Django. Here, whenever I submit the form, validation error didn't appear even though I made mistake in filling form and also validation error isn't visible on the front end. Seek help soon as possible

views.py

from django.shortcuts import render
from testform import form
from django.http import HttpResponse

# Create your views here.

def studentform(request):
    studentrecord=form.Student()
    data={'data':studentrecord}

    if request.method=='POST':
        studentrecord=form.Student(request.POST)
        if studentrecord.is_valid():
           print('validating')
           
           print('sname',studentrecord.cleaned_data['Name'])     
        
        
           print('sloc',studentrecord.cleaned_data['location'])
           print('smail',studentrecord.cleaned_data['mail'])                                   
       

    else:
        print('form is not valid')
        
    return HttpResponse('thanks for form filling')

return render (request,'testform/try.html',context=data)

form.py

from django import forms

class Student(forms.Form):
    Name=forms.CharField()
    location=forms.CharField()
    mail=forms.EmailField()
    course=forms.CharField()


     def clean(self):
         total_clean=super().clean()
         inputname=total_clean['Name']
         if len(inputname)<5:
            raise forms.ValidationError('Type the name in below 5 letters')
    
        input_location=total_clean['location']
        if input_location =='Antartica':
           raise forms.ValidationError('Antartica is not valid')
    
         input_course=total_clean['course']

         if input_course not in ['python','java']:
            raise forms.ValidationError('select either python or java')
2

There are 2 best solutions below

3
Vinita Sonakiya On

I think you missed to add form error tag in html files. Added something like this.

<body>
   <!-- your html elements -->
      {{form.errors}}
</body>
5
willeM_ Van Onsem On

The view logic always will show that the form was filled in correctly, even if it wasn't.

def studentform(request):
    if request.method == 'POST':
        studentrecord = form.Student(request.POST)
        if studentrecord.is_valid():
            print('validating')
            print('sname', studentrecord.cleaned_data['Name'])
            print('sloc', studentrecord.cleaned_data['location'])
            print('smail', studentrecord.cleaned_data['mail'])
            return HttpResponse('thanks for form filling')
    else:
        studentrecord = form.Student()
    data = {'data': studentrecord}
    return render(request, 'testform/try.html', context=data)

In the form, you should also return the cleaned data:

from django import forms

from django import forms


class Student(forms.Form):
    # …

    def clean(self):
        total_clean = super().clean()
        inputname = total_clean['Name']
        if len(inputname) < 5:
            raise forms.ValidationError('Type the name in below 5 letters')

        input_location = total_clean['location']
        if input_location == 'Antartica':
            raise forms.ValidationError('Antartica is not valid')

        input_course = total_clean['course']

        if input_course not in ['python', 'java']:
            raise forms.ValidationError('select either python or java')
        return total_clean