Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do I request a user in DRF?

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

What is request data get in Django?

In this Django tutorial, you will learn how to get data from get request in Django. When you send a request to the server, you can also send some parameters. Generally, we use a GET request to get some data from the server. We can send parameters with the request to get some specific data.

What is request user in Django?

request. user refers to the actual user model instance. request.user.FIELDNAME will allow you to access all the fields of the user model.

How does serializer work on Django REST framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.


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


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

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

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)

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