-1

IntegrityError - Exception Value: null value in column "username_id" of relation "post_comment" violates not-null constraint

I'm building out a comments section for the post app and I'm coming across this error that I can't resolve. This is arising once I submit the comment.body with the form loaded in the views. If possible I would like the authenticated user to automatically be assigned to the username of the comment model as well as the date_added.

models.py

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
    username = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self) -> str:
        return f"{self.post.title} - {self.username}"
    
    def get_absolute_url(self):
        return reverse("new-comment", kwargs={"slug": self.post.slug})

class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=80)
    slug = models.SlugField(max_length=250, null=True, blank=True)
    post_description = models.TextField(max_length=140, null=True, blank=True)
    date_created = models.DateTimeField(default=timezone.now)
    date_updated = models.DateTimeField(auto_now=True)
    main_image = models.ImageField(upload_to="post_pics")
    is_recipe = models.BooleanField()
    ingredients = models.TextField(blank=True, null=True)
    recipe_description = models.TextField(blank=True, null=True)
    cooking_time = models.CharField(max_length=20, blank=True, null=True)
    likes = models.ManyToManyField(User, related_name="post_likes")
    loves = models.ManyToManyField(User, related_name="post_loves")
    drooling_faces = models.ManyToManyField(User, related_name="post_drooling_faces")
    favorite_posts = models.ManyToManyField(
        User, related_name="favorite_posts", default=None, blank=True
    )

forms.py

class NewCommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = [
            "body"
        ]

views.py

def add_comment(request,slug):
    if request.method == "POST":
        form = NewCommentForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.post_slug = {'slug': slug}
            form.save()
            messages.success(request, "Your comment was added successfully.")
            return redirect("food-feed")

        messages.info(
            request,
            "There was an problem trying to add your comment.",
        )
    form = NewCommentForm()
    return render(request, "post/new_comment.html", {"new_comment_form": form})

views.py

path("post/<slug:slug>/new-comment", views.add_comment, name="new-comment")
daniellambert
  • 109
  • 1
  • 8

1 Answers1

0

In order to solve the problem I had to add two lines to the view. By storing the related Post object in a variable post with the argument slug = slug it now works.

def add_comment(request,slug):
    if request.method == "POST":
        form = NewCommentForm(request.POST)
        if form.is_valid():
            form.instance.username = User.objects.get(username=request.user)
            post = Post.objects.get(slug=slug)
            form.instance.post = post
            form.save()
            messages.success(request, "Your comment was added successfully.")
            return redirect("food-feed")
        messages.info(
            request,
            "There was an problem trying to add your comment.",
        )
    form = NewCommentForm()
    return render(request, "post/new_comment.html", {"new_comment_form": form})
daniellambert
  • 109
  • 1
  • 8