get_context_data函数不返回“表单”

时间:2019-01-17 12:55:16

标签: python django django-forms

我具有以下表单的Django代码(django版本1.11):

class MyDocumentUpdateView(UpdateView):
    """ We extend UpdateView as we need to pass self.object in context as resource """
    model = MyDocument

    def get_context_data(self, **context):

        context[self.context_object_name] = self.object
        context['resource'] = self.object
        #context['form'] = self.get_form() <-- if I uncomment this it works
        return context

class DocumentUpdateView(MyDocumentUpdateView):
    form_class = MyDocumentForm
    def form_valid(self, form):
        doc = form.save(commit=False)
        doc.owner = self.request.user
        updateMyDocument(doc, form)
        return HttpResponseRedirect(
            reverse(
                'mydocs_detail',
                args=(
                    self.object.slug,
                )))

运行此代码时,出现错误:

'str' object has no attribute 'fields'

我意识到此错误与 context 变量的返回有关。由于某种原因,上下文词典不包含“表单”。如in the documentation所示:

get_context_data(**kwargs)¶
Calls get_form() and adds the result to the context data with the name ‘form’.

但是在我的情况下,上下文词典不包含“表单”。

如果我使用get_form()def,则一切正常:

context['form'] = self.get_form()

但这对我来说似乎是一个过大的杀手,我想更深入地研究为什么它不起作用。

然后我注意到我使用的是:

def get_context_data(self, **context):

而不是:

def get_context_data(self, **kwargs):

因此,我将上下文定义如下:

context = super(DocumentUpdateView, self).get_context_data(**kwargs)

但是随后出现以下错误:

maximum recursion depth exceeded

1 个答案:

答案 0 :(得分:1)

  

因此,我将上下文定义如下:

context = super(DocumentUpdateView, self).get_context_data(**kwargs)

您使用了错误的类,因为您在MyDocumentUpdateView级别上调用了它,所以它应该是super(MyDocumentUpdateView, self).get_context_data(**kwargs)。因此,您应将其实现为:

class MyDocumentUpdateView(UpdateView):
    """ We extend UpdateView as we need to pass self.object in context as resource """
    model = MyDocument

    def get_context_data(self, **kwargs):
        context = super(MyDocumentUpdateView, self).get_context_data(**kwargs)
        context['resource'] = self.object
        return context

话虽如此,self.object已经添加到上下文中,默认情况下作为模型名称(因此此处为mydocument,您可以通过指定自己指定一个context_object_name属性的值,例如:

class MyDocumentUpdateView(UpdateView):
    """ We extend UpdateView as we need to pass self.object in context as resource """
    model = MyDocument
    context_object_name = 'resource'

在这种情况下,上下文当然不再具有以其模型名称(或任何其他名称)存储的对象。

相关问题