Reputation: 473
I am building a REST API with Django Rest Framework's ViewSets and have come across a problem. When using a POST
request on my API, I can't easily insert the current logged in user into the model.
The model I am serializing is as follows:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Question(models.Model):
op = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
body = models.TextField()
time_created = models.DateTimeField(auto_now_add=True)
The field that is giving me the issue is the op
field, which is a ForeignKey for Django's default User
class.
This API has a POST
URL for creating a new question on the site. I want the viewset to insert the current logged in user into the creation. Other questions have suggested defining a custom create()
method on the serializer, but that doesn't work since I want to insert the current logged in user, and not a set one.
My Serializer:
class QuestionSerializer(ModelSerializer):
class Meta:
model = Question
fields = ("op", "title", "body")
My viewset:
class QuestionViewSet(
mixins.UpdateModelMixin,
mixins.CreateModelMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
GenericViewSet,
):
queryset = Question.objects.all()
serializer_class = QuestionSerializer
Upvotes: 2
Views: 552
Reputation: 4043
Add to your serializer to use the request user:
class QuestionSerializer(ModelSerializer):
op = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = Question
fields = ("op", "title", "body")
Upvotes: 3