在Django中,数据验证通常通过表单类和模型类的字段定义来实现。下面是一些常见的数据验证方法:
from django import forms
class MyForm(forms.Form):
name = forms.CharField()
def clean_name(self):
name = self.cleaned_data['name']
if len(name) < 5:
raise forms.ValidationError("Name must be at least 5 characters long")
return name
from django.db import models
def validate_name_length(value):
if len(value) < 5:
raise ValidationError("Name must be at least 5 characters long")
class MyModel(models.Model):
name = models.CharField(max_length=100, validators=[validate_name_length])
from django.core.validators import MinLengthValidator
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100, validators=[MinLengthValidator(5)])
通过以上方法,可以在Django中实现数据验证,确保数据的完整性和正确性。