0

im a newbie in django and i trying to write api for my django project. im using ModelViewset. this is my veiewset

class TaskModelViewset(ModelViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = TaskSerializer
    queryset = Task.objects.all()

and tis is my serializer

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ['id', 'title', 'complete']

and i using DefaultRouter

router = DefaultRouter()
router.register('task', TaskModelViewset, basename='task')
urlpatterns = router.urls

and this is my Task model:

class Task(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=250)
    complete = models.BooleanField(default=False)

    def __str__(self):
        return self.title

when i trying to post a new task in this url 'http://localhost:8000/todo/api/v1/task/' i encounter this error NOT NULL constraint failed: todo_task.user_id

mehdi
  • 1
  • See [this](https://stackoverflow.com/questions/30203652/how-to-get-request-user-in-django-rest-framework-serializer), [this](https://stackoverflow.com/questions/15770488/return-the-current-user-with-django-rest-framework) and [this](https://stackoverflow.com/questions/64889449/how-to-get-request-user-id-in-django-serializers) – JPG Jul 19 '23 at 09:14
  • did you provide the id of an user. – Tanveer Ahmad Jul 19 '23 at 10:51

1 Answers1

1

I think the problem is that on 'TaskModelViewset' class, 'user' field needs to get automatically populated with current user so you should override 'perform_create' method:

class TaskModelViewset(ModelViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = TaskSerializer
    queryset = Task.objects.all()

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

I hope this helps you.

Kiarash Gh
  • 166
  • 4