I want to update a model using djangorestframework. I don't need to update all fields, so I use PATCH. However, in my form I also have an image field (called 'logo'), which is required for my model. When I try to 'patch' the object and I don't choose a new image for that field, drf throws an error ('logo': 'This field is required').
I know that when using django forms, file fields get a special treatment, meaning that if they already have a value, submitting the form with an empty filefield will just keep the old value. Is there any way to do that using djangorestframework serializers?
Some code for better understanding:
# models.py
class Brand(models.Model):
name = models.CharField(_('name'), max_length=250)
logo = models.ImageField(upload_to='brands/')
# serializers.py
class BrandSerializer(serializers.ModelSerializer):
class Meta:
model = Brand
fields = (
'id',
'name',
'logo',
)
# detail.html
<form method="post" enctype="multipart/form-data">
{%csrf_token%}
<input name="name" type="text" maxlength="30" value="{{ brand.name }}"/>
<input name="logo" type="file" accept="image/*"/>
<input name="_method" type="hidden" value="PATCH">
<input type="submit" value="Update"/>
</form>
The best I could come up with for now was to delete the logo
entry from my request.DATA
before calling the serializer. I am curious if anyone knows a better solution. Thanks.