Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set current user to user field in Django Rest Framework?

I have the following code working perfectly. I can create a Post object from DRF panel by selecting an image and a user. However I want DRF to populate the user field by the currently logged in user.

models.py

class Post(TimeStamped):     user = models.ForeignKey(User)     photo = models.ImageField(upload_to='upload/')     hidden = models.BooleanField(default=False)     upvotes = models.PositiveIntegerField(default=0)     downvotes = models.PositiveIntegerField(default=0)     comments = models.PositiveIntegerField(default=0) 

serializers.py

class PostSerializer(serializers.ModelSerializer):     class Meta:         model = Post         fields = ['id', 'user', 'photo'] 

views.py

class PhotoListAPIView(generics.ListCreateAPIView):     queryset = Post.objects.filter(hidden=False)     serializer_class = PostSerializer     authentication_classes = (SessionAuthentication, BasicAuthentication)     permission_classes = (IsAuthenticated,) 

How can I do this?

like image 404
MiniGunnR Avatar asked Feb 20 '16 02:02

MiniGunnR


People also ask

How do I update user details in Django REST framework?

Open auth/urls.py and add update profile endpoint. we should send a PUT request to API for checking update profile endpoint. We must add username, first_name, last_name and email. If fields passed validations, user profile will be changed.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.


1 Answers

Off the top of my head, you can just override the perform_create() method:

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

Give that a shot and let me know if it works

like image 133
DaveBensonPhillips Avatar answered Sep 25 '22 15:09

DaveBensonPhillips