Make a field optional when POST


I have a ModelSerializer from my Item class.

One of the fields in the serializer is the “user” field which is required so if you create an Item it will always have a user associated with it.

The user field is listed when I send a get request to my endpoint and this is fine.

The problem is when I need to create an Item and send a POST request to my endpoint. I get an error saying the “user” field is required. But I do NOT want to rely on the user sending the correct user id.

I want to be able to set the user by extracting information from the request.

Mosh showed a similar case where he removed the product_id from the fields but this would remove the field from the GET request…

I am using the ListCreateAPIView.

Any advice?

You can do this on the client / form side with some code in the handleSubmit function. Or you can handle it in the API. Not sure where you can find the exact field data you want, not all of it is on the server.

I have an app that uses sessions on the client and I can get different information from that session than I get from the server sessions. Wherever the data is that you are needing, that’s where you extract that field and pass it. If it’s on the client side, just add it as a hidden field or attach it to your POST request programmatically.


You could try using CurrentUserDefault() as a default value for your user-field in the serializer.
Something like this:

class ItemSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(default=serializers.CurrentUserDefault())