如何将表单视图作为django中的上下文传递给另一个视图?

时间:2015-10-08 21:25:08

标签: django django-forms django-templates django-views django-generic-views

我使用Django 1.8创建应用程序。我有一个Link模型和一个Comment模型,它将Link作为ForeignKey。我使用通用视图生成LinkDetailView和CommentCreateView,并将它们显示在单独的模板文件中,然后在链接详细信息模板中包含注释。这是代码:

views.py

class LinkDetailView(DetailView):
    models      = Link
    queryset    = Link.objects.all()

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

class CommentCreateView(CreateView):
    form_class  = CommentForm
    template_name = "comments/comment_form.html"


    def form_valid(self, form):
        link = get_object_or_404(Link, pk=form.data["link"] )
        f = form.save(commit=False)
        f.user = self.request.user
        f.link = link
        f.save()
        return super(CommentCreateView, self).form_valid(form)

link_detail.html

{% block content %}
 . . . 
{% include "comments/comment_form.html" %}
{% endblock %}

comment_form.html

<h2>Add Comment</h2>
<form action="" method="POST">
    {% csrf_token %}
    <table>
        {{ form.as_p }}
    </table>
    <input type="submit" name="submit" value="Submit" />
</form>

表单显示在链接详细信息页面中,但是当我单击“提交”按钮时,它无处可见[我在shell中看到错误"POST /links/1/slug/ HTTP/1.1" 405 0,显然没有保存在数据库中。

我不确定我是否选择了正确的方法来做到这一点,所以任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:3)

我使用FormMixin解决了这个问题,这里是docs

以下是views.py现在的样子:

class LinkDetailView(FormMixin, DetailView):
    models      = Link
    queryset    = Link.objects.all()

    form_class  = CommentForm

    def get_success_url(self):
        return reverse('link_detail', kwargs={'pk': self.object.pk, 'slug': self.object.slug})

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

    def post(self, request, *args, **kwargs):
        if not request.user.is_authenticated():
            return HttpResponseForbidden()
        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):
        link = get_object_or_404(Link, pk=self.object.pk)
        print link
        f = form.save(commit=False)
        f.user = self.request.user
        f.link = link
        f.save()
        return super(LinkDetailView, self).form_valid(form)