【问题标题】:How can I implement FormView into DetailView, django如何将 FormView 实现为 DetailView,django
【发布时间】:2015-12-24 17:19:43
【问题描述】:

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

我的意见.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>

它什么也不显示:(

我该怎么办?

【问题讨论】:

  • 你能检查你的 html 看看是否有&lt;form method="post" action="" role="form"&gt; 吗?
  • 是的!它在那里:&lt;form method="post" action="" role="form"&gt; {{ form }} &lt;/form&gt;

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


【解决方案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>

【讨论】:

    猜你喜欢
    • 2017-05-30
    • 2013-05-31
    • 2022-11-06
    • 2018-01-21
    • 2020-09-18
    • 2016-12-14
    • 1970-01-01
    • 2020-11-08
    • 2020-04-21
    相关资源
    最近更新 更多