混合 Detail View 和 Form Mixin django 的问题

Problem with mixing Detail View and Form Mixin django

我正在尝试使用 Django 为我的应用程序的博客部分创建一个评论系统。我试图将我的详细视图与表单 mixin 混合,但我有点挣扎。提交表单后,它不会保存并且不会出现错误。如果有人能提供帮助,我将不胜感激。

这是我的观点

class DetailPostView(FormMixin, DetailView):
    model = Post
    template_name = "blog/post_detail.html"
    context_object_name = "posts"
    form_class = CommentForm

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["form"] = CommentForm
        return context

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def get_success_url(self):
        return reverse("post-detail", kwargs={"pk": self.object.pk})

模特

class Comment(models.Model):
    comment = models.ForeignKey(Post, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    content = models.TextField()
    author = models.CharField(max_length=50)
    created_on = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_on"]

    def __str__(self):
        return self.title

发生这种情况的原因是因为您构建了一个传递给上下文数据的新表单,因此它不会呈现任何错误,因为您构建了一个没有的表单 验证请求数据并呈现该表单,因此您不会首先显示拒绝数据的表单。

但你不需要那样做。 Django 的 FormMixin [Django-doc] already takes care of that. You thus should not override the .get_context_data(…) method [Django-doc].

另一个问题是你没有保存你的表单,你可以覆盖form_valid方法,或者你可以继承自ModelFormMixin [Django-doc].

最后你最好先创建表单,然后赋值self.object,否则它将作为实例传递给表单:

from django.views.generic.edit import <b>ModelFormMixin</b>

class DetailPostView(<b>ModelFormMixin</b>, DetailView):
    model = Post
    template_name = 'blog/post_detail.html'
    context_object_name = 'posts'
    form_class = CommentForm

    # <i>no</i> get_context_data override

    def post(self, request, *args, **kwargs):
        # first construct the form to avoid using it as instance
        form = self.get_form()
        self.object = self.get_object()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

    def get_success_url(self):
        return reverse('post-detail', kwargs={'pk': self.object.pk})