[Answered ]-Django DetailView with form for comments

1👍

Setting a temporary variable like this and you won’t have to set an initial value in ArticleView

Simply as this

context['form'] = self.get_form()

and this

 def form_valid(self, form):
           new_comment = form.save(commit=False)
           new_comment.post = self.get_object()
           return super(ArticleView, self).form_valid(form)

1👍

I solved it, kind of..

class ArticleView(FormMixin, DetailView):
    model = Article
    template_name = 'template/article.html'
    form_class = CommentForm

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

    def get_context_data(self, **kwargs):
        context = super(ArticleView, self).get_context_data(**kwargs)
        context['form'] = CommentForm(initial={
            'article': self.object
        })
        context['comments'] = self.object.comment_set.filter(approved=True)
        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):
        form.save()
        return super(ArticleView, self).form_valid(form)

in forms.py:

class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        exclude = ('admitted',)
        widgets = {
            'article': forms.HiddenInput()
        }

The only way I could… set a value for that article field (which is a foreign key for the article) was to set initial value in ArticleView.

If someone have a better alternative, I’m glad too see it.

0👍

I know it’s been years, but maybe my answer will be useful for someone
Yierstem’s answer worked for me, but I made a few changes

First, changed get_success_url in order to use parent model’s get_absolute_url:

def get_success_url(self):
    return self.object.get_absolute_url()

Add get_absolute_url method to parent model first:

def get_absolute_url(self):
    return reverse('record_detail', args=[str(self.pk)]

Second, I add my target article and author (ForeignKey(s) of my Comment model) inside form_valid method:

def form_valid(self, form):
    new_comment = form.save(commit=False)
    new_comment.target = self.object
    new_comment.author = self.request.user
    new_comment.save()
    return super(RecordDetailView, self).form_valid(form)

Leave a comment