Django rest框架imagefield可选 [英] Django rest framework imagefield optional

查看:69
本文介绍了Django rest框架imagefield可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

models.py

models.py

picture = models.ImageField(upload_to='Images/', 
                            default='/Images/None/No-img.jpg', blank=True,null=True)

serializers.py

serializers.py

class UserProfileSerializer(serializers.ModelSerializer):
    picture = serializers.ImageField(max_length=None, 
                                     allow_empty_file=True, use_url=True)

    class Meta:
        model = UserProfile
        fields = ('id','picture',)     
        read_only_fields=('id')

但是它仍然显示为必填字段,我无法通过图片发出发布请求,这是一个错误吗?

But it's still showing as a required field, I can't make post request with image, is it a bug?

推荐答案

也许您应该尝试在序列化程序中将字段 picture 设置为 required = False .

Maybe you should try setting the field picture as required=False in your serializer.

由于您定义的 image 字段没有任何 required 参数,因此DRF假定默认的 required 值即 True .如果您在反序列化过程中未提供此字段,则DRF会引发错误,提示您需要 image 字段.

Since you have defined the image field without any required parameter, DRF is assuming the default required value i.e. True. If you don't supply this field during deserialization, DRF will raise an error that image field is required.

文档:

如果在此期间未提供字段,通常会引发错误反序列化.如果不需要此字段,则设置为false在反序列化过程中存在.

Normally an error will be raised if a field is not supplied during deserialization. Set to false if this field is not required to be present during deserialization.

默认为 True .

Defaults to True.

 class UserProfileSerializer(serializers.ModelSerializer):
    picture = serializers.ImageField(required=False, max_length=None, 
                                     allow_empty_file=True, use_url=True)

这篇关于Django rest框架imagefield可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆