iblogc

Django 表单自定义验证

2017-07-23 · 3 min read
Django

Model

第一种

def validate_begins(value):
    if not value.startswith(u'new'):
        raise ValidationError(u'Must start with new')
 
 
class Post(models.Model):
    title = models.CharField('标题', max_length=100,
                             validators=[validate_begins])
    body = models.CharField('内容', max_length=1000)

第二种

class Post(models.Model):
    title = models.CharField('标题', max_length=100,
                             validators=[validate_begins])
    body = models.CharField('内容', max_length=1000)
 
    def clean_fields(self, exclude=None):
        # 验证模型的所有字段
        if exclude:
            # 禁用掉自定义的字段验证
            exclude.append('body')
        super(Post, self).clean_fields(exclude)
        if not self.title.startswith(u'new'):
            raise ValidationError({'title':u'Must start with new'})

第三种

class Post(models.Model):
    title = models.CharField('标题', max_length=100,
                             validators=[validate_begins])
    body = models.CharField('内容', max_length=1000)
 
    def clean(self):
        super(Post, self).clean()
        if not self.title.startswith(u'new'):
            raise ValidationError({'title':u'Must start with new'})

Form

第四种

def validate_begins(value):
    if not value.startswith(u'new'):
        raise ValidationError(u'Must start with new')

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'body']
    def __init__(self, *args, **kwargs):
        super(PostForm, self).__init__(*args, **kwargs)
        self.fields["title"].validators.append(validate_begins)

第五种

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'body']
 
    def clean_title(self):
        title = self.cleaned['title']
        if not title.startswith(u'new'):
            raise ValidationError(u'Must start with new')
        return title

第六种

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'body']
     
    # django1.7之前此方法必须返回一个cleaned_data字典,但现在可选
    def clean(self):
        cleaned_data = super(PostForm, self).clean()
        if not cleaned_data['title'].startswith('new'):
            raise forms.ValidationError({'title': u'Must start with new'})

第七种

def validate_begins(value):
    if not value.startswith(u'new'):
        raise ValidationError(u'Must start with new')

class PostForm(forms.ModelForm):
    author =  forms.CharField('标题', max_length=100,
                             validators=[validate_begins])
    class Meta:
        model = Post
        fields = ['title', 'body']

第八种

from django import forms
from django.core.validators import validate_email
 
class MultiEmailField(forms.Field):
    def to_python(self, value):
        "Normalize data to a list of strings."
 
        # Return an empty list if no input was given.
        if not value:
            return []
        return value.split(',')
 
    def validate(self, value):
        "Check if value consists only of valid emails."
 
        # Use the parent's handling of required fields, etc.
        super(MultiEmailField, self).validate(value)
 
        for email in value:
            validate_email(email)
Powered by Gridea && Deployed by 部署状态