Django的.选择字段的初始值动态 [英] Django. Initial value of Choice Field dynamically
本文介绍了Django的.选择字段的初始值动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在视图中动态设置选择字段的初始值.但这不起作用,不确定是什么错误:
I'm trying to set the initial value of a Choice Field dynamically, in the view. But it doesn't work, not sure what is wrong:
views.py
...
form = FormEditGroup(initial={
'choices_a': group.get_a(),
'choices_i': group.get_i(),
})
get_a()
是返回打开"或关闭"的模型方法, get_i()
返回管理员"或全部".
get_a()
is a model method that returns "open" or "closed", get_i()
returns "admins" or "all".
forms.py
class FormEditGroup(forms.Form):
choices_a = (("closed", "Closed"), ("open", "Open"))
choices_i = (("all", "All"), ("admins", "Admins"))
a = forms.ChoiceField(... choices=choices_a),
i = forms.ChoiceField(... choices=choices_i),
没有将初始值设置为 get_a()
或 get_i()
返回的值.
It is not setting the initial value to what get_a()
or get_i()
return.
推荐答案
您应将 initial
词典中的表单字段名称作为键传递.
You should pass the form field names in the initial
dictionary as keys.
此参数(如果提供)应为字典映射字段名称初始值.
更改您的'choices_a'
和'choices_i'
键,以分别形成字段名称 a
和 i
.
Change your 'choices_a'
and 'choices_i'
keys to form field names a
and i
respectively.
尝试以下代码:
form = FormEditGroup(initial={
'a': group.get_a(), # initial value for 'a'
'i': group.get_i(), # initial value for 'i'
})
这篇关于Django的.选择字段的初始值动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文