简体   繁体   English

如何在FormView中将FormView实现为Django

[英]How can I implement FormView into DetailView, django

I use Django based views. 我使用基于Django的视图。 I have one class that displays the object(DetailView) and now I want to add a form to the same page, as in the DetailView. 我有一个显示对象(DetailView)的类,现在我想将表单添加到同一页面,就像在DetailView中一样。

My views.py: 我的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

Maybe, you understand - BlogFullPostView - display page, where I want to add form. 也许您了解-BlogFullPostView-显示页面,我想在其中添加表单。 CommentFormView - view for comment. CommentFormView-查看评论。

My form: 我的表格:

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)

So, in template, I try to add form: 因此,在模板中,我尝试添加表单:

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

And it does not display anything :( 它不显示任何内容:(

What should I do? 我该怎么办?

I would not try to mix logic for both usecase in a single view. 我不会尝试在单个视图中混合两个用例的逻辑。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM