如何在Django的DetailView中具有来自另一个模型的表单?

时间:2019-04-08 18:34:46

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

我正在使用Django,我想做的是拥有一个帖子的DetailView,并且在该细节视图中,我想要一个带有用于发表评论的表单的评论部分。当我加载详细视图时,它不会显示注释的形式,我正在使用基于类的视图作为表单的详细信息。 我的models.py看起来像这样:

class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length = 200)
text = models.TextField()
created_date = models.DateTimeField(default = timezone.now)
likes = models.IntegerField(default=0)
tags = models.CharField(max_length = 50, default = '' )

def get_absolute_url(self):
    return reverse('blog:post_list')

def __str__(self):
    return self.title

class Comments(models.Model):
    post = models.ForeignKey('blog.Post', related_name='comments', on_delete=models.CASCADE)
    text = models.TextField()
    created_date = models.DateTimeField(default = timezone.now)

views.py看起来像这样:

class PostDetailView(DetailView):
    form_class = CommentsForm
    model = Post

表单如下:

   class CommentsForm(forms.ModelForm):
        class Meta:
            model = Comments
            fields = ('text',)

            widgets = {
                'text' : forms.Textarea(attrs={'class':'comment-textarea'})
            }

comments_form.html看起来像这样:

<div class="container">
    <div class="row">
        <div class="col">
            <h1>Estoy siendo insertado</h1>
            <form action="" method="POST">
                {%csrf_token%}
                {{ form.as_p }}
                <input type="submit" class="btn mt-2 btn-comments" value="Comment">
            </form>
        </div>
    </div>
</div>

1 个答案:

答案 0 :(得分:1)

这是因为DetailView无法处理form_class。您在这里有一些选择:

  • 通过get_context_data
  • 提供表格
  • FormMixin上应用DetailView。 (可以在django.view.generic.edit下找到)

上下文数据示例:

def get_context_data(self, **kwargs):
    context = super(PostDetailView, self).get_context_data(**kwargs)
    context['comments_form'] = CommentsForm()
    return context