验证REST端点上的字段

时间:2019-02-04 05:52:37

标签: django django-models django-forms django-rest-framework django-views

我有一个端点,该端点在被调用时应该更新或创建用户的个人资料。在此终结点内部,需要创建或更新3个字段(avatar, bio, gender)当前,我正在像这样使用UpdateAPIView

class UpdateOrCreateProfile(UpdateAPIView):
    serializer_class = ProfileSerializer

    def get_object(self):
        return Profile.objects.get(user=self.request.user) 

序列化器类如下:

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = '__all__'

这很好,但是验证无法正常进行。显示的表单具有clean_avatar函数,该函数不接受200x200 px以下的图像。像这样:

class ProfileForm(ModelForm):
    avatar = forms.ImageField(required=False, widget=forms.FileInput)
    bio = forms.CharField(widget=forms.Textarea(attrs={'rows': 3, "placeholder": "Bio"}), max_length=200,
                          required=False)
    class Meta:
        model = Profile
        fields = ['avatar', 'bio', 'gender']

    def clean_avatar(self):
        picture = self.cleaned_data.get("avatar")
        if picture:
            w, h = get_image_dimensions(picture)
            if w < 200:
                raise forms.ValidationError("The image is %i pixel wide. It's supposed to be more than 200px" % w)
            if h < 200:
                raise forms.ValidationError("The image is %i pixel high. It's supposed to be 200px" % h)
        return picture

我该如何做,以便在终端上也进行与表单上相同的验证?

1 个答案:

答案 0 :(得分:0)

您可以编写一个validate_avtar方法,它作为表单清洁方法工作。

class ProfileSerializer(serializers.ModelSerializer):
   class Meta:
      model = Profile
      fields = '__all__'

   def validate_avatar(self, picture):
     if picture:
        w, h = get_image_dimensions(picture)
        if w < 200:
            raise serializers.ValidationError("The image is %i pixel wide. It's supposed to be more than 200px" % w)
        if h < 200:
            raise serializers.ValidationError("The image is %i pixel high. It's supposed to be 200px" % h)
     return picture