Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-views

null value in column "user_id" of relation "core_bedroomsummary" violates not-null constraint | DETAIL: Failing row contains (2, title, string, null)


I feel like this should be so easy to resolve but i cant seem to figure out why its not pulling the specific users uuid. The whole point is for the user to be able to have their own comments.

views.py

class BedroomSummaryViewSet(mixins.DestroyModelMixin,
                            mixins.UpdateModelMixin,
                            mixins.ListModelMixin,
                            mixins.CreateModelMixin,
                            viewsets.GenericViewSet):
    """Manage comments in the database."""
    serializer_class = serializers.BedroomSummarySerializer
    queryset = BedroomSummary.objects.all()
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        """Filter queryset to authenticated user."""
        return self.queryset.filter(user=self.request.user).order_by('-title')

serializers.py

class BedroomSummarySerializer(serializers.ModelSerializer):
    """Serializer for interior summary."""

    class Meta:
        model = BedroomSummary
        fields = ['id', 'title', 'comment']
        read_only_field = ['id']

models.py

class BedroomSummary(models.Model):
    """Bedroom Summary Model"""
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    title = models.CharField(max_length=55)
    comment = models.CharField(max_length=2000)

Solution

  • You need to inject the user in the item you create, so:

    from rest_framework.viewsets import ModelViewSet
    
    
    class BedroomSummaryViewSet(ModelViewSet):
        # …
    
        def perform_create(self, serializer):
            serializer.save(user=self.request.user)