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.
CodePudding user response:
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.
Any data the user submits through a form will be passed to the server as strings. It doesn't matter which type of form field was used to create the form.
Eventually, the browser would will everything as strings. When Django cleans the data it automatically converts data to the appropriate type.
For example IntegerField data would be converted to an integer
In Django, this cleaned and validated data is commonly known as cleaned data.
We can access cleaned data via cleaned_data dictionary:
name = form.cleaned_data['name']
CodePudding user response:
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.
CodePudding user response:
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.
CodePudding user response:
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.