Django - Validation(验证器)

http://wiki.jikexueyuan.com/project/django-chinese-docs-1.8/13-12-data-validation.html

示例:

# -----
from django.core.exceptions import ValidationError

def validate_even(value):
    if value % 2 != 0:
        raise ValidationError('%s is not an even number' % value)

# ----
from django.db import models

class MyModel(models.Model):
    even_field = models.IntegerField(validators=[validate_even])

# -----
from django import forms

class MyForm(forms.Form):
    even_field = forms.IntegerField(validators=[validate_even])


自定义异常返回

raise serializers.ValidationError(detail={"code": "403", "message": "权限不足"})

推荐阅读更多精彩内容