尽管字段为空,但序列化器is_valid()返回true

时间:2018-10-17 16:56:34

标签: django django-rest-framework

我尝试并使用基于函数的视图运行代码,它运行良好,然后我尝试切换到modelViewSet。

这是我的序列化器代码:

UserSerializer

public $timeout = 180;

这是我的modelViewSet:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        username = serializers.CharField(required=True)
        email = email = serializers.EmailField(validators=[UniqueValidator(queryset=get_user_model().objects.all())])
        phone = serializers.CharField(required=True)
        full_name = serializers.CharField(required=True)
        user_type = serializers.CharField(required=True)
        password = serializers.CharField(write_only=True)
        fields=('username', 'email', 'phone', 'full_name', 'user_type','password')

    def create(self, validated_data):

        user = get_user_model().objects.create(
            username=validated_data['username'],
            email=validated_data['email'],
            phone=validated_data['phone'],
            full_name=validated_data['full_name'],
            user_type=validated_data['user_type']
        )
        user.set_password(validated_data['password'])
        user.save()

        return user

现在,如果我不传递用户名或密码,则userSerializer的is_valid会出错,但是如果我不传递电子邮件或电话或full_name,is_valid不会引发任何异常,并且它保持为真。

它在基于函数的视图中正常工作,或者可能是我遗漏了一些东西。

我担心的是,如果request.data中缺少任何值,应该给出错误

1 个答案:

答案 0 :(得分:4)

串行器的字段应定义为序列化器的属性,而不是meta的属性:

class UserSerializer(serializers.ModelSerializer):
    username = serializers.CharField(required=True)
    email = serializers.EmailField(validators=[UniqueValidator(queryset=get_user_model().objects.all())])
    phone = serializers.CharField(required=True)
    full_name = serializers.CharField(required=True)
    user_type = serializers.CharField(required=True)
    password = serializers.CharField(write_only=True)

    class Meta:
        model = get_user_model()
        fields=('username', 'email', 'phone', 'full_name', 'user_type','password') 

使用您当前的代码required=True自变量无效。