DRF - 序列化之验证用户发送的数据

views.py:

from rest_framework.views import APIView
from rest_framework import serializers
from django.shortcuts import HttpResponse


class UserGroupSerializer(serializers.Serializer):
    title = serializers.CharField()


class UserGroupView(APIView):
    def post(self, request, *args, **kwargs):
        ser = UserGroupSerializer(data=request.data)
        if ser.is_valid():  # 如果 ser 有数据
            print(ser.validated_data["title"])
        else:
            print(ser.errors)  # 如果没数据,则打印错误信息
        return HttpResponse("ok")

提交数据

因为内容为空,打印错误信息:

提交有效的数据:

打印结果:

可自定义提交空内容时的错误提示信息

from rest_framework.views import APIView
from rest_framework import serializers
from django.shortcuts import HttpResponse


class UserGroupSerializer(serializers.Serializer):
    title = serializers.CharField(error_messages={"blank": "标题不能为空"}, )


class UserGroupView(APIView):
    def post(self, request, *args, **kwargs):
        ser = UserGroupSerializer(data=request.data)
        if ser.is_valid():  # 如果 ser 有数据
            print(ser.validated_data["title"])
        else:
            print(ser.errors)  # 如果没数据,则打印错误信息
        return HttpResponse("ok")

再次提交空信息:

 

posted @ 2021-01-19 20:22  Sch01aR#  阅读(108)  评论(0编辑  收藏  举报