I am getting null value in column "user_id" violates not-null constraint, how can I get foreign key data to register on my comment form?

Viewed 43

This my models.py file

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager

class UserAccountManager(BaseUserManager):
    def create_user(self, name, email, password, **other_fields):
        if not email:
            raise ValueError('Users must have an email adress')
    
        email = self.normalize_email(email)
        user = self.model(name=name, email=email, password=password)
    
        user.set_password(password)
        user.save()

        return user

    def create_superuser(self, name, email, password = None, **other_fields):
    
        other_fields.setdefault('is_staff', True)
        other_fields.setdefault('is_superuser', True)
        other_fields.setdefault('is_active', True)

    return self.create_user(name=name, email=email, password = password, is_superuser=True)


class UserAccount(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=355, unique=False)
    is_superuser = models.BooleanField(default=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=True)

    objects = UserAccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

    def __str__(self):
        return str(self.id)

I have a foreign key on my comment model, I tested this on django admin and it works fine, but with my comment form, the foreign key isn't populating, i just get "null value in column "user_id" violates not-null constraint", I dont know what im doing wrong

class Comment(models.Model):
   
  comment = models.CharField(max_length=250)
  user = models.ForeignKey(UserAccount, on_delete=models.CASCADE)


 def __str__(self):
     return str(self.user.id)

serializers.py

from djoser.serializers import UserCreateSerializer
from django.contrib.auth import get_user_model
from rest_framework.serializers import ModelSerializer
from accounts.models import Comment
User = get_user_model()

class UserCreateSerializer(UserCreateSerializer):
    class Meta(UserCreateSerializer.Meta):
        model = User
        fields = ('id', 'name',  'email', 'password') 
I am reffering my foreign key user as a field, i'm not sure if that is correct.
class CommentSerializer(ModelSerializer):
    class Meta:
       model = Comment
       fields=('id', 'comment', 'user')

viewsets.py

from rest_framework import viewsets
from . import models
from . import serializers

class CommentViewset(viewsets.ModelViewSet):
queryset = models.Comment.objects.all()
serializer_class = serializers.CommentSerializer

router.py

from accounts.viewsets import CommentViewset
from rest_framework import routers

router = routers.DefaultRouter()
router.register('comment', CommentViewset)
1 Answers

You need to add user_id field for writing in the serializer.

class CommentSerializer(ModelSerializer):

    class Meta:
        model = Comment
        fields=('id', 'comment', 'user')
        extra_kwargs = {
            'user': { 'read_only': True }
        }

    def create(self, validated_data):
        new_comment = Comment(**validated_data)
        new_comment.user_id = self.context['request'].user.id
        new_comment.save()
        return new_comment
Related