9

我正在尝试在基于 Django 类的视图中处理两种表单。该站点包含一个名为form(基于GET)的表单,用于缩小 ListView 的列表结果和第二个表单status_form(基于POST)。

两种形式都是必需的,因为 ListView 返回项目列表。Form让用户限制选择并status_forms让用户通过模式表单标记不正确的项目(因此它需要在同一个模板中)。

我的麻烦是ListView该方法没有附带post,但是FormView有。我的类List继承自两个类,但是当我执行该类时,我收到错误消息:

属性错误:“列表”对象没有属性“status_form”

我应该如何更改我的实现以允许通过post method?

class List(PaginationMixin, ListView, FormMixin):
    model = ListModel
    context_object_name = 'list_objects'
    template_name = 'pages/list.html'
    paginate_by = 10 #how may items per page

    def get(self, request, *args, **kwargs):
        self.form = ListSearchForm(self.request.GET or None,)
        return super(List, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.status_form = StatusForm(self.request.POST or None)
        if self.status_form.is_valid():
            ...
        else:
            return super(List, self).post(request, *args, **kwargs)

    def get_queryset(self):
        # define the queryset
        ...
        # when done, pass to object_list
        return object_list

    def get_context_data(self, **kwargs):
        context = super(List, self).get_context_data(**kwargs)
        context.update(**kwargs)
        context['form'] = self.form
        context['status_form'] = self.status_form # Django is complaining that status_form is not existing, result since the post method is not executed
        return context
4

1 回答 1

7
# Django is complaining that status_form does not exist,
# result since the post method is not executed
context['status_form'] = self.status_form

因为你一开始没有定义self.status_from。您已经在 中定义了它get_context_data,并且可以从那里访问它。

get_context_data您可以从您的 post 方法中访问您的对象;

context = self.get_context_data(**kwargs)
status_form = context['status_form']

还要考虑您可以status_form直接在方法本身中定义您的方法,而无需从or中post获取它。selfget_context_data

重新设计您的视图以将每个表单处理分开在单独的视图中,然后将它们彼此紧密。

视图重新设计:

简而言之,让每个视图做一项工作。您可以创建一个仅用于处理您的视图并将其status_form命名为StatusFormProcessView然后在您的List视图中返回它的post方法

class List(ListView);
    def post(self, request, *args, **kwargs):
        return StatusFormView.as_view()(request) # What ever you need be pass to you form processing view

这只是一个例子,需要更多的工作才能成为现实。

再举一个例子;在我的网站索引页面上,我有一个搜索表单。当用户POSTGET搜索表单时,我的搜索处理不存在IndexView,而是我在单独的视图中处理整个表单的东西,如果表单应该处理GET方法,我将覆盖get()方法,如果表单应该处理POST,我' ll overridepost()方法将search_form数据发送到负责处理处理的视图search_form

评论回复

status_form = context['status_form']

不应该

context['status_form'] = status_form

在我创建它之后?

你想从中得到status_formcontext所以你需要

status_form = context['status_form']

无论如何,您的表单数据可在self.request.POST

于 2013-03-25T18:49:07.847 回答