IntegrityError - 表单提交时 Django 中数据库关系的异常值

IntegrityError - Exception Value with DB relations in Django on form submission

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

我正在为 post 应用构建一个评论部分,但我遇到了这个我无法解决的错误。一旦我提交 comment.body 并在视图中加载了表单,就会出现这种情况。如果可能的话,我希望经过身份验证的用户自动分配给评论模型的用户名以及 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")

为了解决这个问题,我不得不在视图中添加两行。通过使用参数 slug = slug 将相关 Post 对象存储在变量 post 中,它现在可以工作了。

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})