是否可以在ListView模板中使用表单?

时间:2013-09-06 18:21:54

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

我构建了一个列表视图,它可以正常工作,并且能够提供我想要的内容。

在这个ListView的模板中,我声明了一个指向CreateView的表单。 表格是这样的,

{% if user.is_authenticated %}
<form action="{% url 'post_wall' %}" method="POST">
    {% csrf_token %}
    <input type='text' name='body' />
    <input type='hidden' name='from_user' value='{{ user.id }}' />
    <input type='hidden' name='to_user' value='{{ to_user }}' />
    <input type='submit' value='POST'/>
</form>
{% endif %}

post_wall网址对应

url(r'accounts/post_wall', WallCreate.as_view(), name='post_wall'),

包含表单的网址是

url(r'accounts/wall/(?P<slug>\w+)/$', WallList.as_view(), name='wall'),

这会调用CreateView,

class WallCreate(CreateView):
    model = WallPost

    def get_success_url(self):
        url = reverse('wall', kwargs={'slug': request.POST.to_user})
        return HttpResponseRedirect(url)

这给了我一个

TemplateDoesNotExist at /accounts/post_wall
users/wallpost_form.html

当帖子发送到CreateView时,这不应该正常吗?或者我误解了有关CBV的事情?

1 个答案:

答案 0 :(得分:6)

是的,但所有表单流程都必须由ListView本身完成。这很简单,考虑到你可以继承ModelFormMixin的行为。您只需要一个网址(列表视图)。模板看起来像:

{% if user.is_authenticated %}
<form action="" method="POST">
    {% csrf_token %}
    {{ form }}
    <input type='submit' value='POST'/>
</form>
{% endif %}

您的观点:

from django.views.generic.list import ListView
from django.views.generic.edit import ModelFormMixin

class ListWithForm(ListView, ModelFormMixin):
    model = MyModel
    form_class = MyModelForm

    def get(self, request, *args, **kwargs):
        self.object = None
        self.form = self.get_form(self.form_class)
        # Explicitly states what get to call:
        return ListView.get(self, request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        # When the form is submitted, it will enter here
        self.object = None
        self.form = self.get_form(self.form_class)

        if self.form.is_valid():
            self.object = self.form.save()
            # Here ou may consider creating a new instance of form_class(),
            # so that the form will come clean.

        # Whether the form validates or not, the view will be rendered by get()
        return self.get(request, *args, **kwargs)

    def get_context_data(self, *args, **kwargs):
        # Just include the form
        context = super(ListWithForm, self).get_context_data(*args, **kwargs)
        context['form'] = self.form
        return context