How to get Request User in Django-Rest-Framework serializer

0 votes

I've tried something like this, it does not work.

class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post

    def save(self):
        user = self.context['request.user']
        title = self.validated_data['title']
        article = self.validated_data['article']

I need a way of being able to access request.user from my Serializer class.

Aug 12, 2020 in Python by kartik
• 37,520 points
13,542 views

1 answer to this question.

0 votes

Hello @kartik,

You cannot access the request.user directly. You need to access the request object, and then fetch the user attribute.

Like this:

user =  self.context['request'].user

Or to be more safe,

user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
    user = request.user

Hope it helps!!

Thank you!!

answered Aug 12, 2020 by Niroj
• 82,880 points

Related Questions In Python

0 votes
1 answer

How to return custom JSON in Django REST Framework?

Hello @kartik, There are 2 ways to custom ...READ MORE

answered Jun 25, 2020 in Python by Niroj
• 82,880 points
11,112 views
0 votes
1 answer

How to add annotate data in django-rest-framework queryset responses?

Hello @kartik, The queryset returned from get_queryset provides ...READ MORE

answered Jun 25, 2020 in Python by Niroj
• 82,880 points
6,081 views
0 votes
1 answer

How to secure APIs for Registration and Login in Django Rest Framework?

Hello @kartik, you cannot have an authentication system ...READ MORE

answered Jun 25, 2020 in Python by Niroj
• 82,880 points
2,794 views
0 votes
1 answer

How to disable a method in a ViewSet, django-rest-framework

Hello @kartik, You could keep using viewsets.ModelViewSet and define http_method_names on your ...READ MORE

answered Jun 26, 2020 in Python by Niroj
• 82,880 points
10,733 views
0 votes
1 answer

How to update user password in Django Rest Framework?

Hello @kartik, Using a modelserializer might be an ...READ MORE

answered Jul 1, 2020 in Python by Niroj
• 82,880 points
9,118 views
0 votes
1 answer

How to return the current user with Django Rest Framework?

Hello @kartik, The best way is to use ...READ MORE

answered Jun 25, 2020 in Python by Niroj
• 82,880 points
11,897 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP