gpt4 book ai didi

python - get_context_data 函数不返回 'form'

转载 作者:行者123 更新时间:2023-12-01 08:26:11 24 4
gpt4 key购买 nike

我有以下表单的 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

最佳答案

So I defined the context as following:

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

您使用了错误的类,因为您在MyDocumentUpdateView处调用了它级别,应该是super(<b>MyDocumentUpdateView</b>, 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):
<b>context = super(MyDocumentUpdateView, self).get_context_data(**kwargs)</b>
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
<b>context_object_name = 'resource'</b>

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

关于python - get_context_data 函数不返回 'form',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54236431/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com