I'm trying to execute an update through my API
. When I push an update, I do not have all the required fields, because I'm only trying to update the ones that have changed. I get a 400 "This field is required."
error.
I know the field is required, but I'm trying to just update, not put in all my required fields again. This is a PUT
request. This occurs before create or update are called on my serializers
. It fails on the is_valid()
call (which I do not override). Honestly, there isn't any relevant code to show. To fix this do I have to override is_valid and provide a password there?
For example: Password is a required field in my model. However I only push "first_name" because that's the only field that changed. I will get: password":["This field is required."]
.
UPDATE
is possible via 2 requests: PUT and PATCH
PUT
updates all the fields of the object on which the operation is to be performed. It basically iterates over all the fields and updates them one by one. Thus, if a required field is not found in the supplied data, it will raise an error.
PATCH
is what we call a Partial Update. You can update only the fields that are needed to be changed. Thus, in your case change your request method to PATCH
and your work will be done.
I was facing the same error after many experiments found something, so added all fields in serializer.py
in class meta, as shown below -
class Emp_UniSerializer( serializers.ModelSerializer ):
class Meta:
model = table
fields = '__all__' # To fetch For All Fields
extra_kwargs = {'std_code': {'required': False},'uni_code': {'required': False},'last_name': {'required': False},'first_name': {'required': False}}
Here, we can update any field, it won't show error ["This field is required."]
Add partial = True
argument in serializer as such:
serializer = BookSerializer(book, data=request.data, partial=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With