sshussain270
sshussain270

Reputation: 1865

How to add current user into a field in django model serializer

I am developing an application in django-rest-framework. Following is my serializer:

class MySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = My
        fields = ('user','title','description')

The problem is that when I run it, it asks for the user to be selected like this:

enter image description here

I want that whichever user is logged in, he should be added to user field automatically. In django website development, I used to do it using request.user but how do I do it in django rest framework?

Upvotes: 1

Views: 1926

Answers (3)

Prakash S
Prakash S

Reputation: 652

If you extend django view generic classes then you can add in views.py

from rest_framework.permissions import IsAuthenticate

class MyView(generics.ListCreateAPIView):
    permission_classes = (IsAuthenticated,)
    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

And then in serializers.py

class MySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = My
        fields = ('user','title','description')
        read_only_fields = ('user',) # Add this

Upvotes: 1

shady
shady

Reputation: 455

You would do something like the class

MySerializer(serializers.HyperlinkedModelSerializer):
    user = serializers.ReadOnlyField()
    class Meta:
        model = My
        fields = ('user','title','description')

When you call the serializer, you just add the current user into the serializer, either in views.py or in serializer create method.

  1. In views.py

    serializer.save(user=request.user)

  2. In serializer create method

    def create(self, validated_data): validated_data['user'] = request.user.id obj = ExampleModel.objects.create(**validated_data) return obj

Upvotes: 0

Hisagr
Hisagr

Reputation: 621

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.

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

More details here: http://www.django-rest-framework.org/api-guide/validators/#currentuserdefault

Hope this will help

Upvotes: 0

Related Questions