如何将FormView实现为DetailView,django

时间:2015-12-24 17:19:44

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

我使用基于Django的视图。我有一个显示对象的类(DetailView),现在我想将一个表单添加到同一页面,就像在DetailView中一样。

我的views.py:

class CommentFormView(FormView):
    form_class = AddCommentForm
    success_url = '/'

class BlogFullPostView(CommentFormView, DetailView):
    model = Post
    template_name = 'full_post.html'
    pk_url_kwarg = 'post_id'
    context_object_name = 'post'

    def get_context_data(self, **kwargs):
        context = super(BlogFullPostView, self).get_context_data(**kwargs)
        context['comments'] = Comment.objects.filter(post=self.object)
        return context

也许,你了解 - BlogFullPostView - 显示页面,我要添加表单。 CommentFormView - 查看评论。

我的表格:

class AddCommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('content',)
        widgets = {
            'content': forms.TextInput(attrs={
                'class': 'form-control'
            })
        }

        labels = {
            'content': 'Content'
        }

    def __init__(self, *args, **kwargs):
        super(AddCommentForm, self).__init__(*args, **kwargs)

所以,在模板中,我尝试添加表单:

<form method="post" action="" role="form">
     {{ form }}
</form>

它没有显示任何内容:(

我该怎么办?

1 个答案:

答案 0 :(得分:1)

我不会尝试在单个视图中混合两个用例的逻辑。

class BlogFullPostView(DetailView):
    model = Post
    template_name = 'full_post.html'
    pk_url_kwarg = 'post_id'
    context_object_name = 'post'

    def get_context_data(self, **kwargs):
        context = super(BlogFullPostView, self).get_context_data(**kwargs)
        context['comments'] = Comment.objects.filter(post=self.object)
        context['form'] = AddCommentForm(initial={'post': self.object })
        return context

class CommentFormView(FormView):
    form_class = AddCommentForm

    def get_success_url(self):
        # logic here for post url 


# full_post.html

<form method="post" action="{% url "comment_form_view_url" %}">
    {{ form }}
</form>