64

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:

class Activity(models.Model):
    number = models.PositiveIntegerField(
        blank=True, null=True, help_text="Activity number. For record keeping only.")
    instructions = models.TextField()
    difficulty = models.ForeignKey(Difficulty)
    categories = models.ManyToManyField(Category)
    boosters = models.ManyToManyField(Booster)

    class Meta():
        verbose_name_plural = "Activities"

My serializer:

class ActivitySerializer(serializers.ModelSerializer):

    class Meta:
        model = Activity

And my view:

class ActivityDetail(generics.RetrieveUpdateDestroyAPIView):

    queryset = Activity.objects.all()
    serializer_class = ActivityDetailSerializer

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

{
    "id": 1, 
    "difficulty": 1, 
    "categories": [
        1
    ], 
    "boosters": [
        1
    ],
    "current_user": 1 //Current authenticated user here
}
Jamie Counsell
  • 7,730
  • 6
  • 46
  • 81

4 Answers4

89

I found the answer looking through the DRF source code.

class ActivitySerializer(serializers.ModelSerializer):
    
    # Create a custom method field
    current_user = serializers.SerializerMethodField('_user')

    # Use this method for the custom field
    def _user(self, obj):
        request = self.context.get('request', None)
        if request:
            return request.user

    class Meta:
        model = Activity
        # Add our custom method to the fields of the serializer
        fields = ('id','current_user')

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:

serializer = ActivitySerializer(
    data=request.data,
    context={
        'request': request
    }
)
Lis
  • 555
  • 4
  • 26
Jamie Counsell
  • 7,730
  • 6
  • 46
  • 81
  • How do you access that variable? I have set mine up similarly, but in the create() method, I can't seem to access the variable. It's also not in the request.POST. – Craig Jul 27 '15 at 15:16
  • I used above code but giving following error File "/Users/abc/abc/Django/Work/abc/abc/src/MadhaparGamApps/serializers/newsfeedSerializer.py", line 21, in _user user = self.context['request'].user KeyError: 'request' – Pinank Lakhani Sep 15 '16 at 12:19
  • 3
    For everyone who's getting the request KeyError: You can solve this is by initializing the serializer from the view with the request object as follows: serializer = serializers.RandomSerializer(data=request.data, context={'request':request}) Source: http://www.django-rest-framework.org/api-guide/serializers/#saving-instances – Braden Holt Nov 12 '17 at 21:14
  • 2
    @Braden Holt Thanks dude, you saved a lot of time for me – inmate_37 Apr 24 '18 at 12:03
  • Do you know where DRF insert the request information in serializer's context in it's source code?? – dogewang Oct 31 '18 at 03:08
  • @dogewang https://github.com/encode/django-rest-framework/blob/0e10d32fb122619a7977909536b642d09603192a/rest_framework/generics.py#L132 called at https://github.com/encode/django-rest-framework/blob/0e10d32fb122619a7977909536b642d09603192a/rest_framework/generics.py#L111 – Jamie Counsell Oct 31 '18 at 19:28
67

A context is passed to the serializer in REST framework, which contains the request by default. So you can just use self.context['request'].user inside your serializer.

codwell
  • 739
  • 5
  • 10
  • Do you know where DRF insert the request information in serializer's context in it's source code?? – dogewang Oct 31 '18 at 03:10
  • 1
    This is not true any more, you will need to pass an extra context to the serializer. See https://www.django-rest-framework.org/api-guide/serializers/#including-extra-context – Akshay Apr 29 '19 at 00:45
  • 1
    @Akshay Strange, it still works for me without explicitly passing the context down as of DRF 3.9.4. – phoenix Jul 18 '19 at 16:28
4

I had a similar problem - I tried to save the model that consist user in, and when I tried to use user = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault()) like on official documentation - but it throws an error that user is 'null'. Rewrite the default create method and get a user from request helped for me:

class FavoriteApartmentsSerializer(serializers.ModelSerializer):
user = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault())

class Meta:
    model = FavoriteApartments
    exclude = (
        'date_added',
    )

def create(self, validated_data):
    favoriteApartment = FavoriteApartments(
        apartment=validated_data['apartment'],
        user=self.context['request'].user
    )
    favoriteApartment.save()
    return favoriteApartment
Ashen One
  • 371
  • 1
  • 12
-2

I modified the request.data:

serializer = SectionSerializer(data=add_profile_data(request.data, request.user))

def add_profile_data(data, user):
    data['user'] = user.profile.id
    return data
stderr
  • 8,567
  • 1
  • 34
  • 50