Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest framework imagefield optional

models.py

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

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?

like image 926
thisisms Avatar asked Jun 07 '16 12:06

thisisms


1 Answers

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

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.

From the docs:

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.

Defaults to True.

 class UserProfileSerializer(serializers.ModelSerializer):
    picture = serializers.ImageField(required=False, max_length=None, 
                                     allow_empty_file=True, use_url=True)
like image 71
Rahul Gupta Avatar answered Sep 28 '22 06:09

Rahul Gupta