214

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.

Yevgeniy Shchemelev
  • 3,601
  • 2
  • 32
  • 39
PythonIsGreat
  • 7,529
  • 7
  • 21
  • 26
  • 6
    DRF `CurrentUserDefault` is absolutely ❤️ http://www.django-rest-framework.org/api-guide/validators/#currentuserdefault – andilabs Mar 02 '18 at 14:02

15 Answers15

375

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

More on extra context can be read here

karthikr
  • 97,368
  • 26
  • 197
  • 188
  • 2
    it says `NameError: name 'self' is not defined` – Coderaemon Jan 05 '16 at 12:10
  • 2
    of course, this was in the context of a class. You are most likely not in the context of a class – karthikr Jan 06 '16 at 01:43
  • 4
    In my serializer, in `validate()` method, self.context is an empty dict. Why? – David Dahan Feb 07 '16 at 17:17
  • 23
    David - you probably solved this long ago, but if anyone else has this issue, it could be because you are constructing your serializer manually. I had this problem in a nested serializer instantiated for a generic relationship. The docs say to do serializer = NoteSerializer(value) but this will only pass your instance, not the context containing the request. You can pass kwargs to the constructor and send it the info it needs (see get_serializer or GenericAPIView for how it does it) – Jon Vaughan Feb 10 '17 at 12:11
  • 3
    @JonVaughan any detail how to pass kwargs to the serializer instance?? –  Aug 25 '17 at 07:37
  • Adding to @JonVaughan comment you can call the method get_serializer_context just like GenericAPIView does: `serializer_class = self.get_serializer_class() kwargs['context'] = self.get_serializer_context() return serializer_class(*args, **kwargs)` – Duilio Mar 17 '21 at 16:42
87

Actually, you don't have to bother with context. There is a much better way to do it:

from rest_framework.fields import CurrentUserDefault

class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post

   def save(self):
        user = CurrentUserDefault()  # <= magic!
        title = self.validated_data['title']
        article = self.validated_data['article']
Ihor Pomaranskyy
  • 5,437
  • 34
  • 37
  • 3
    It did not work,its returning a Null object. user_edit = serializers.CurrentUserDefault() – Enderson Menezes Jul 08 '19 at 13:20
  • 2
    @EndersonMenezes It's probably best worked with the `IsAuthenticated` permission. – Micheal J. Roberts Aug 17 '20 at 13:25
  • Not fully related, but interesting: I have readwrite PrimaryKeyRelatedField and I need to filter possibilities (which are users addresses) for current user only. I made derrived class MyAddresses(PrimaryKeyRelatedField) and I try rewrite get_queryset() there using .filter(user=..). I have problem to get request.user there. Additionally I have no success with user=CurrentUserDefault(). However I have success and can access the user by calling it: CurrentUserDefault()(self) makes the trick. [self relates to the MyAddresses class/object] – mirek Oct 01 '20 at 11:11
59

As Igor mentioned in other answer, you can use CurrentUserDefault. If you do not want to override save method just for this, then use doc:

from rest_framework import serializers

class PostSerializer(serializers.ModelSerializer):
    user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault())
    class Meta:
        model = Post
haccks
  • 104,019
  • 25
  • 176
  • 264
IJR
  • 1,288
  • 13
  • 14
  • doc link is now mislinked. – coler-j May 03 '19 at 23:04
  • Link to the official DRF documentation with this same example https://www.django-rest-framework.org/api-guide/serializers/#specifying-read-only-fields – Paolo Melchiorre Feb 21 '20 at 11:39
  • 2
    I used `HiddenField` instead of `PrimaryKeyRelatedField` without read `read_only` attiribute, it works. As I understood there is no security problem. – ishak O. Dec 19 '20 at 15:40
17

Use this code in view:

serializer = UploadFilesSerializer(data=request.data, context={'request': request})

then access it with this in serializer:

user = self.context.get("request").user
Mehran Jalili
  • 585
  • 7
  • 18
12

CurrentUserDefault A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer.

in views.py

serializer = UploadFilesSerializer(data=request.data, context={'request': request})

This is example to pass request

in serializers.py

owner = serializers.HiddenField(
    default=serializers.CurrentUserDefault()
)

Source From Rest Framework

Paulo Mendonça
  • 635
  • 12
  • 28
Sameer
  • 121
  • 1
  • 3
10

For those who used Django's ORM and added the user as a foreign key, they will need to include the user's entire object, and I was only able to do this in the create method and removing the mandatory field:

class PostSerializer(serializers.ModelSerializer):

def create(self, validated_data):
    
    request = self.context.get("request")
    
    post = Post()
    post.title = validated_data['title']
    post.article = validated_data['article']
    post.user = request.user

    post.save()

    return post

class Meta:
    model = Post
    fields = '__all__'
    extra_kwargs = {'user': {'required': False}}
Fernando Tholl
  • 2,587
  • 2
  • 16
  • 14
7

You can pass request.user when calling .save(...) inside a view:

class EventSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Event
        exclude = ['user']


class EventView(APIView):

    def post(self, request):
        es = EventSerializer(data=request.data)
        if es.is_valid():
            es.save(user=self.request.user)
            return Response(status=status.HTTP_201_CREATED)
        return Response(data=es.errors, status=status.HTTP_400_BAD_REQUEST)

This is the model:

class Event(models.Model):
    user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    date = models.DateTimeField(default=timezone.now)
    place = models.CharField(max_length=255)
Max Malysh
  • 29,384
  • 19
  • 111
  • 115
  • The `exclude = ['user']` did the job for me. I had declared it as `write_only = True` but with your solution is not needed anymore. Much more clear than defining it as `read_only = True` – George Bikas Oct 09 '20 at 04:46
5

In GET method:

Add context={'user': request.user} in the View class:

class ContentView(generics.ListAPIView):
    def get(self, request, format=None):
        content_list = <Respective-Model>.objects.all()
        serializer = ContentSerializer(content_list, many=True, 
                                       context={'user': request.user})

Get it in the Serializer class method:

class ContentSerializer(serializers.ModelSerializer):
    rate = serializers.SerializerMethodField()

    def get_rate(self, instance):
        user = self.context.get("user") 
        ...  
    ...

In POST method:

Follow other answers (e.g. Max's answer).

Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150
4

You need a small edit in your serializer:

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']

Here is an example, using Model mixing viewsets. In create method you can find the proper way of calling the serializer. get_serializer method fills the context dictionary properly. If you need to use a different serializer then defined on the viewset, see the update method on how to initiate the serializer with context dictionary, which also passes the request object to serializer.

class SignupViewSet(mixins.UpdateModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet):

    http_method_names = ["put", "post"]
    serializer_class = PostSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        kwargs['context'] = self.get_serializer_context()
        serializer = PostSerializer(instance, data=request.data, partial=partial, **kwargs)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)    
        return Response(serializer.data)
cgl
  • 1,106
  • 1
  • 13
  • 27
4

You can not access self.context.user directly. First you have to pass the context inside you serializer. For this follow steps bellow:

  1. Some where inside your api view:

     class ApiView(views.APIView):
         def get(self, request):
             items = Item.object.all()
             return Response(
                 ItemSerializer(
                      items, 
                      many=True,
                      context=request  # <- this line (pass the request as context)
                 ).data
             )
    
  2. Then inside your serializer:

     class ItemSerializer(serializers.ModelSerializer):
         current_user = serializers.SerializerMethodField('get_user')
    
         class Meta:
             model = Item
             fields = (
                 'id',
                 'name',
                 'current_user',
             )
    
         def get_user(self, obj):
             request = self.context
             return request.user  # <- here is current your user 
    
3

The solution can be simple for this however I tried accessing using self.contenxt['request'].user but not working in the serializer.

If you're using DRF obviously login via token is the only source or maybe others that's debatable.

Moving toward a solution.

Pass the request.user instance while creating serializer.create

views.py

if serializer.is_valid():
            watch = serializer.create(serializer.data, request.user)

serializer.py

 def create(self, validated_data, usr):
    return Watch.objects.create(user=usr, movie=movie_obj, action=validated_data['action'])
Singham
  • 303
  • 2
  • 8
1

The best way to get current user inside serializer is like this.

AnySerializer(data={
        'example_id': id
    }, context={'request': request})

This has to be written in views.py And now in Serializer.py part

user = serializers.CharField(default=serializers.CurrentUserDefault())

This "user" must be your field in Model as any relation like foreign key

Gkr
  • 41
  • 3
0

If you are using generic views and you want to inject current user at the point of saving the instance then you can override perform_create or perform_update:

def perform_create(self, serializer):
    serializer.save(user=self.request.user)

user will be added as an attribute to kwargs and you can access it through validated_data in serializer

user = validated_data['user']
haccks
  • 104,019
  • 25
  • 176
  • 264
0

drf srz page

in my project it worked my user field was read only so i needed to get user id in the create method

class CommentSerializer(serializers.ModelSerializer):
    comment_replis = RecursiveField(many=True, read_only=True)
    user = UserSerializer(read_only=True)

    class Meta:
        model = PostComment
        fields = ('_all_')

    def create(self, validated_data):
 


        post = PostComment.objects.create(**validated_data)   
        print(self._dict_['_kwargs']['data']["user"]) # geting #request.data["user"] #  <- mian code
        post.user=User.objects.get(id=self._dict_['_kwargs']['data']["user"])
        return post


in my project i tried this way and it work

ali lotfi
  • 11
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 10 '22 at 10:04
  • You need to call `post.save()` after you called `post.user=...`, else the relation wont be stored in the database. – jmangold Aug 26 '22 at 12:04
0

as others answered, should use self.context['request'].user , but consider it does not work with GenericAPIView , should use ListAPIView or RetrieveAPIView

while GenericAPIView does not send request context to serializer

hadi ahadi
  • 116
  • 1
  • 1
  • 6