Django Rest Framework - How to set the current_user when POST

Viewed 190

I have just followed a small tutorial using DRF, but I can't figure how to like my model to his user when POSTing a new object

this is my model :

# Create your models here.
class Project(models.Model):
  # project title
  title = models.CharField(max_length=255, null=False)
  # subtitle
  subtitle = models.CharField(max_length=255, null=False)

  #######

  user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)

and so my serializer


class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = ("id", "title", "subtitle", "user_id")

so, now in the view I have access to the current_user with this : request.user


class ListProjectsView(generics.ListCreateAPIView):

    authentication_classes = [authentication.TokenAuthentication]

    queryset = Project.objects.all()
    serializer_class = ProjectSerializer

    def list(self, request):
        queryset = Project.objects.filter(user_id=request.user.id)
        serializer = ProjectSerializer(queryset, many=True)
        return Response(serializer.data)

[...]

    def create(self, request, pk = None):
      return super(ListProjectsView, self).create(request, pk = None)


I suppose there is a way to passe the request.user is the create in order to allow my Project.user_id to be filled ?

Whatever I'm doing, I can't manage to set the user, and i get the django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint error

Any idea?

Thanks!

2 Answers

Try to override with following method. Everytime PUT/PATCH/CREATE operation is performed following method is called. This is the good way to pass the current user.

   def perform_create(self, serializer):
        serializer.save(user = self.request.user)
class Project(models.Model):
  # project title
  title = models.CharField(max_length=255, null=False)
  # subtitle
  subtitle = models.CharField(max_length=255, null=False)
  user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)

okay so you have FK user but try to access it with the user_id = request.user.id

Just call

queryset = Project.objects.filter(user=request.user)

queryset = Project.objects.filter (user_id=request.user.id)

if you want to match the id you should put two __ like so user__id = request.user.id but I dont see any sence making it.

Related