What's the difference between Cleaned data and is valid in django

161 Views Asked by At

What is the difference between cleaned_data and is_valid functions in django?, I just came across forms and immediately i got stuck there

can anyone play with some simple examples. I've read many documentation but i cant able to differentiate it.

3

There are 3 best solutions below

0
On

Cleaned data: Clean data are valid, accurate, complete, consistent, unique, and uniform. (Dirty data include inconsistencies and errors.)

Cleaned data valid in django: It uses uses a clean and easy approach to validate data. The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

0
On

EXAMPLE

 def InsertData(request):
        form = Student()
        if request.method == 'POST':
            form = Student(request.POST,request.FILES)
            if form.is_valid():
                fname = form.cleaned_data['fname']
                lname = form.cleaned_data['lname']
                email = form.cleaned_data['email']
                password1 = form.cleaned_data['password1']
                password2 = form.cleaned_data['password2']
                if password1 == password2:
                    form.save()
                    messages.success(request,'Student Successfully Inserted')
                    return redirect('/home/')
                else:
                    messages.error(request,'Password does not match !')
                    return redirect('/home/')
        context= {'form':form,}
        return render(request,'home.html',context)
    
    
    ### If we have used clean data in password1 and password2, then we can give condition that password1 and password2 must be same and it's length must be bigger then 7 we can do with the help of clean data and is_valid() will check that data is valid or not if it is valid then it will save the data.
1
On
  1. is_valid() method is used to perform validation for each field of the form.

  2. cleaned_data is where all validated fields are stored.