VIewDemo
class RegUserSet(mixins.CreateModelMixin,viewsets.GenericViewSet): serializer_class = RegUserSerializer # queryset = User.objects.all()
SerializerDemo
class RegUserSerializer(serializers.ModelSerializer): code = serializers.CharField(required=True, max_length=10, write_only=True) mobile = serializers.CharField(max_length=11, allow_null=True) password = serializers.CharField(write_only=True) def validate_code(self, code): mobile = self.initial_data['username'] codes = VerifyCode.objects.filter(mobile=mobile).order_by('-add_time') if codes: dbcode = codes[0] if dbcode.code != code: raise serializers.ValidationError("验证码不正确") if dbcode.add_time.replace(tzinfo=None) < datetime.datetime.now() - datetime.timedelta(days=0, minutes=5, seconds=0): raise serializers.ValidationError("验证码过期") else: raise serializers.ValidationError('验证码不正确') return code def validate(self, attrs): attrs['mobile'] = attrs['username'] del attrs['code'] return attrs def create(self, validated_data): user = super(RegUserSerializer, self).create(validated_data) user.set_password(validated_data['password']) user.save() return user class Meta: model = User fields = ('username', 'password', 'mobile', 'code')