Home > Net >  optional values Django-rest-Framework
optional values Django-rest-Framework

Time:09-26

I am building API in Django-rest-framework but I have a model which has two main fields The request should be valid if user submit one field at least, he can submit both of them the problem is when I build the serializer I am getting error for set optional Fields

here is my code

models.py

class KG(models.Model):
   content = models.TextField() 
   image = models.ImageField(upload_to=nameFile, validators = [FileExtensionValidator(['png','jpg','jpeg'])],blank=True)

serializer.py

class KGSerializer(ModelSerializer):
    class Meta:
        model = KG
        fields = ['content',]

    def __init__(self, *args, **kwargs):
        if self.image:
            self.Meta.fields = list(self.Meta.fields)
            self.Meta.fields.append('image')
        super(PostSerializer, self).__init__( *args, **kwargs)

views

class createPostAPIView(APIView):

def post(self, request):
    data = request.data

    content = data['content']
    image = data['image']
    

    serializer = KGSerializer(data=data)
    serializer.is_valid(raise_exception=True)
    serializer.save()

    return Response(serializer.data)

but when I request without image I get

This QueryDict instance is immutable

is there a way to allow any field to be optional

CodePudding user response:

Yes there is a way, you could try this

class BillingRecordSerializer(serializers.ModelSerializer):
def validate(self, attrs):
    # Apply custom validation either here, or in the view.

class Meta:
    fields = ['client', 'date', 'amount']
    extra_kwargs = {'client': {'required': False}}
    validators = []  # Remove a default "unique together" constraint.

For any additional info please check this link

  • Related