首页 > 解决方案 > Django UpdateView 中的 {{ form.object }}

问题描述

根据文档, UpdateViewself.object存在

模板:

{% block content %}

<p>
    {{ form.object.some_foreign_key }}
</p>

<form method="post">
    {{ form.as_p }}
    <input type="submit" value="Update">
</form>

{% endblock %}

form.object不存在:

失败:“/foo/bar_form.html”中未定义的模板变量“form.object”

为什么form.object模板中不存在?

标签: djangodjango-templates

解决方案


似乎您将UpdateView类属性object与注入的模板上下文form实例混淆了

表单实例的设置方式与您执行基于函数的视图时的设置方式相同,并且self.object设置为form.instance

ModelFormMixin

def get_form_kwargs(self):
    """Return the keyword arguments for instantiating the form."""
    kwargs = super().get_form_kwargs()
    if hasattr(self, 'object'):
        kwargs.update({'instance': self.object})
    return kwargs

此外,您可以检查例如 get() 方法ProcessFormView并通过实现get_context_datainFormMixin


推荐阅读