python - Access a form method from generic.UpdateView in Django
问题描述
I have a view which is a generic.UpdateView
, and I need to access a form method - get_hidden_fields()
. How do I access it?
I currently used self.form_class().get_hidden_fields()
but I'm not sure if this is correct. I think it creates a new instance of the form and I want to use the current instance.
def get_context_data(self, **kwargs):
cd = super().get_context_data(**kwargs)
cd.update({
'matches_list': self.page.object_list,
'form_hidden_fields': list(self.form_class().get_hidden_fields()),
})
return cd
https://github.com/speedy-net/speedy-net/blob/staging/speedy/match/matches/views.py#L54
解决方案
我可以直接从模板访问表单方法:
{% if field.name in form.get_hidden_fields %}
但是,如果我需要从 Python 访问表单,我认为正确的方法是使用cd['form']
in get_context_data
(在调用之后cd = super().get_context_data(**kwargs)
)。
def get_context_data(self, **kwargs):
cd = super().get_context_data(**kwargs)
cd.update({
'matches_list': self.page.object_list,
'form_hidden_fields': list(cd['form'].get_hidden_fields()),
})
return cd
推荐阅读
- android - 回收站中的 CardView 图像在平板电脑上滚动时放大太多
- c++ - 使用 lambda 初始化多维数组
- python - 如何在测验中添加下一个和上一个 [python]
- ssl - 访问 asmx 服务抛出错误无法为具有权限的 SSL/TLS 建立安全通道 - 虽然可以从 SOAPUI 工作
- performance - 提高 Haskell 中递归的效率
- parallel-processing - Julia 中的并行计算——在多核上运行一个简单的 for 循环
- javascript - 如何在 JavaScript 中处理 Object.prototype
- database - 在批处理模式下使用 Alembic 更改 sa.Column 可为空的属性
- python - Scipy Minimize - 无法最小化目标函数
- javascript - 调试石头剪刀布游戏?Javascript