DJango中表单验证和数据清理的区别

huwehgph  于 2022-12-27  发布在  Go
关注(0)|答案(1)|浏览(135)

我已经在DJango中了解了表单验证的基本概念,但是我很难理解在DJango中清理数据到底意味着什么?清理和验证之间有什么区别?

kqqjbcuj

kqqjbcuj1#

  • Django提供了clean()方法来从字段中获取值并对其进行操作。
  • 让我来解释一下。
  • 假设我有一个表单,名为StudentRegistration(forms.Form),并且有三个字段(name、email和roll_no)。
  • 在表单API Django中提供clean_field()clean()方法来验证数据
  • 这里clean_field()clean()方法从表单获取数据,使用clean_field()clean()从表单获取数据后,您可以根据需要进行验证

--------示例-------------

class StudentRegistration(forms.Form):
    name=forms.CharField()
    email=forms.EmailField()
    roll_no=forms.IntegerField()

    # -------- DJango Validation [clean_field()] -------- validate using clean_field() method.
    def clean_name(self):
        name = self.cleaned_data['name']
        if len(name) < 2:
            raise forms.ValidationError('Name should be more than 2 character')
        else:
            return name

    # -------- Validate data using [clean()] method ------- validate using clean() method.
    def clean(self):
        cleaned_data = super().clean()
        valname=self.cleaned_data['name']
        valroll_no=self.cleaned_data['roll_no']
        if len(valname)<2:
            raise forms.ValidationError('Name should be more than 2 character')
        if len(roll_no) == 0:
            raise forms.ValidationError('Roll number should be gater than 0')

您也可以在类似的视图中验证数据。

def InsertData(request):
    student_data = Student.objects.all() # Show data of Student Table
    if request.method == 'POST':
        form = Student(request.POST,request.FILES)
        if form.is_valid():

            name = form.cleaned_data['name']
            roll_no = form.cleaned_data['roll_no']
            if len(name)<2:
                print("Name should be more than 2 character")
            if len(roll_no) == 0:
                print("Roll number should be gater than 0")

            form.save()
            messages.success(request,'Student Successfully Inserted')
            return redirect('/home/')
    else:
        form = Student()
    context= {'form':form,'student_data':student_data}
    return render(request,'home.html',context)
简而言之,cleaned_data、clean()和clean_field()方法的作用是从用户输入的Form中获取纯数据,并对其进行一些操作。
这里我把Django提供的表单验证的所有方法的代码
# -------- DJango Validation [clean_fieldname] -------- validate using clean_field() method.
def clean_name(self):
    name = self.cleaned_data['name']
    if len(name) < 2:
        raise forms.ValidationError('Enter > 2')
    else:
        return name

#-------- DJango Validation [ clean() ] -------- validate using clean() method.
class StudentRegistration(forms.Form):
 name=forms.CharField()
 email=forms.EmailField()

 def clean(self):
    cleaned_data = super().clean()
    valname=self.cleaned_data['name']
    valemail=self.cleaned_data['email']
    if len(valname)<4:
        raise forms.ValidationError('Name should be more than or equal 4')
    if len(valemail)<10:
        raise forms.ValidationError('Email should be more than or equal 10')

#-------- DJango Validation By [Built-in Validators] -------- validate using Built-in Validators.
forms.py
form django.core import validators
from django import forms
class StudentRegistration(forms.Form):
    name=forms.CharField(validators=[validators.MaxLengthValidator(10)])
    email=forms.EmailField()

#-------- DJango Validation By [Custom Validators] -------- validate using Custom Validators.
form django.core import validators
from django import forms

def starts_with_s(value):
 if vaule[0] != 's':
    raise forms.ValidationError('Name should start with s')

class StudentRegistration(forms.Form):
 name=forms.CharField(validators=[starts_with_s])
 email=forms.EmailField()

相关问题