如何使用FormMixin在帖子DetailView中获取数据到模板?

时间:2018-05-14 15:43:48

标签: python django django-class-based-views

我有以下代码,想知道如何在同一视图中显示表单中保存的数据?我有Post的Detailview,以及在同一视图中回答这篇文章的表格,但我如何显示从这个表格中保存的数据?

class PostDetailView(FormMixin, DetailView):
    model = Post
    form_class = AnswerForm
    template_name = 'main/postdetail.html'
    context_object_name = 'posts'


    def get_success_url(self):
       return reverse('postdetail', kwargs={'slug': self.object.slug})

    def get_context_data(self, **kwargs):
        context = super(PostDetailView, self).get_context_data(**kwargs)
        context['form'] = AnswerForm(initial={'post': self.object})
        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 form_valid(self, form):
        instance = form.save(commit=False)
        instance.created_by = self.request.user
        instance.post = self.object
        instance.save()
        return super(PostDetailView, self).form_valid(form)

我的模特

class Answer(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE,)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE,)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    content = models.TextField()

1 个答案:

答案 0 :(得分:0)

您在成功发布请求后重定向,因此您无法显示表单数据。

看起来重定向已回到帖子详细信息视图。在模板中,您可以显示相关答案以及帖子:

{{ posts }}
{% for answer in posts.answer_set.all %}
    {{ answer.created_by }}
    {{ answer.content }}
{% endfor %}

使用context_object_name = 'posts'令人困惑,因为您正在显示单个post的详细信息。我建议你将视图更改为:

class PostDetailView(FormMixin, DetailView):
    model = Post
    form_class = AnswerForm
    template_name = 'main/postdetail.html'
    context_object_name = 'post'  # or just remove this line since the default will be 'post'

然后,您将在模板中显示相关答案:

{{ post }}
{% for answer in post.answer_set.all %}
    {{ answer.created_by }}
    {{ answer.content }}
{% endfor %}