基于Django类的视图和注释

时间:2015-12-22 19:34:20

标签: django django-class-based-views

我在向基于类的视图添加注释时遇到问题, forms.py:

  class RequestForm(ModelForm):
      class Meta:
          model = Request
          exclude = ('slug',)
  class RequestCommentForm(ModelForm):
      class Meta:
          model = RequestComment
          fields = ['body' ]

models.py:

class Request(models.Model):
    title = models.CharField(max_length=250 )
    date = models.DateTimeField('Request date', default=timezone.now, editable=False )
    department = models.CharField(max_length=2, choices=DEPARTMENT)
    support_request = models.TextField('Request', max_length=2500, blank=True)
    owner = models.ForeignKey(User,)
    slug = models.SlugField(blank=True, editable=False)

    def __unicode__(self):
        return self.title

views.py:

class RequestDetailView(ModelFormMixin, DetailView):
    model = Request
    form_class = RequestCommentForm

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

    def get_context_data(self, **kwargs):
        context = super(RequestDetailView, self).get_context_data(**kwargs)
        context['form'] = self.get_form()
        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.instance.author = self.request.user
        form.instance.request = Request.objects.get(pk=self.object.pk)
        form.instance.created = timezone.now
        form.save()
Also tried this part with:
        self.object = form.save(commit=False)
        self.object.author = self.request.user
        self.object.request = Request.objects.get(pk=self.object.pk)
        self.object.created = timezone.now
        self.object.save()
        return super(RequestDetailView, self).form_valid(form)

模板:request_detail.html评论部分.....

{% load bootstrap %}
<form action="{% url 'request-detail' object.id %}" method="post"> {% csrf_token %}
        <ul class="form-group">
        {{ form|bootstrap }}
        </ul>
        <input class="btn btn-primary" type="submit" value="Submit" />
</form>

.....

页面呈现正确,但是当我提交时,请不要保存评论。

调试工具栏显示sql查询正在更新请求模型,而不是请求注释。

无法弄清楚如何将不同模型的简单评论表添加到详细页面。 任何帮助将不胜感激。

此外,如果有更优雅的方式将评论表单添加到基于类的视图,很想看到它。我的google-fu并没有帮助我找到任何东西。

2 个答案:

答案 0 :(得分:0)

希望我能找到一种方法用CBV做到这一点,但是nope ..功能视图效果很好......

class RequestDetailView(ModelFormMixin, DetailView):
    model = Request
    form_class = RequestCommentForm

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

    def get_context_data(self, **kwargs):
        context = super(RequestDetailView, self).get_context_data(**kwargs)
        context['form'] = self.get_form()
        return context

    def comments(self):
        return RequestComment.objects.filter(request=Request.objects.get(pk=self.object.pk))


def RequestCommentAddView(request, pk):
    form = RequestCommentForm(request.POST or None)

    if form.is_valid() and pk:
        form.instance.author = request.user
        form.instance.request = Request.objects.get(pk=pk)
        form.save()
        return HttpResponseRedirect(reverse('request-detail', kwargs={'pk': pk}))
    return HttpResponseRedirect(reverse('request-detail', kwargs={'pk': pk}))

答案 1 :(得分:0)

我知道我回答得太晚了,但是将来也许有人遇到同样的问题可能会受益。

Class RequestDetailView(DetailView):
    model = Request
    template_name = 'detail.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context ['comment'] = RequestComment.objects. all()
        context['form'] = RequestCommentForm()
        return context


Class CommentCreateView(CreateView):
    model = RequestComment
    form_class = RequestCommentForm

    def get_success_URL(self):
        return reverse ('request: detail', kwargs = {'slug':self.object.post.slug})

    def form_valid(self, form):
        post = get_object_or_404(Request, slug = self.kwargs ['slug'])
        Form.instance.post = Request
        return super().form_valid(form)

URL

path('<slug:slug>/add_comment/', CommentCreateView.as_view(), name = add_comment')

最后是HTML

    <form action="{% url 'request:add_comment' request.slug %}" enctype = "multiparty/form-data" method = "post">
    </form>

就是这样。我用手机回答了,所以有一些错别字。这是我的第一个答案,我在堆栈溢出中搜索了答案,稍后再发布链接。我假设RequestComment外键字段是post,在Django中不鼓励创建名称为'request'的模型。