Q-bart
Q-bart

Reputation: 1591

How can I implement FormView into DetailView, django

I use Django based views. 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.

My 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. CommentFormView - view for comment.

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?

Upvotes: 0

Views: 606

Answers (1)

mishbah
mishbah

Reputation: 5597

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>

Upvotes: 1

Related Questions