Skip to content
Advertisement

Get current user in Model Serializer

Is it possible to get the current user in a model serializer? I’d like to do so without having to branch away from generics, as it’s an otherwise simple task that must be done.

My model:

JavaScript

My serializer:

JavaScript

And my view:

JavaScript

How can I get the model returned, with an additional field user such that my response looks like this:

JavaScript

Advertisement

Answer

I found the answer looking through the DRF source code.

JavaScript

The key is the fact that methods defined inside a ModelSerializer have access to their own context, which always includes the request (which contains a user when one is authenticated). Since my permissions are for only authenticated users, there should always be something here.

This can also be done in other built-in djangorestframework serializers.

As Braden Holt pointed out, if your user is still empty (ie _user is returning None), it may be because the serializer was not initialized with the request as part of the context. To fix this, simply add the request context when initializing the serializer:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement