Alexey K
Alexey K

Reputation: 6723

Django Rest Framework - Extending the existing User model and saving it

I have a Profile model, that is connected to user by OneToOne field. How can I alter my process of profile creation in order to associate user with profile ? I use token auth.

class ProfileCreateSerializer(ModelSerializer):
    class Meta:
          model = Profile
          fields = [
              'name',
              'age',
              'heigth',
              'location',
          ]

class ProfileCreateAPIView(CreateAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileCreateSerializer

Upvotes: 0

Views: 330

Answers (1)

Rahul Gupta
Rahul Gupta

Reputation: 47846

If you want to save the currently loggedin user, you can override the perform_create() method of the ProfileCreateAPIView.

In that method, you can pass the user argument with value as request.user. DRF will use this extra value along with the fields defined in the serializer to create Profile instance.

class ProfileCreateAPIView(CreateAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileCreateSerializer

    def perform_create(self, serializer):        
        serializer.save(user=self.request.user) # pass the user field 

Upvotes: 1

Related Questions