如何在Django的choicefield中动态设置选项?
我想动态设置选项。
我使用了 __set_choices 方法,但是当请求方式是 POST 的时候,is_valid 方法总是返回 False。
if request.method=='POST':
_form = MyForm(request.POST)
if _form.is_valid():
#something to do
5 个回答
2
在一个视图里,你可以这样做:
--views.py
lstChoices = _getMyChoices()
form.fields['myChoiceField'].choices = lstChoices
这里的 lstChoices 是一个动态生成的元组列表,用来表示你的选择项。
4
关键是要明白,choices
可以是任何一种可迭代的东西:
import uuid
from itertools import count
class MyForm(BaseForm):
counter = count(1)
@staticmethod
def my_choices():
yield (uuid.uuid1, next(counter))
afield = forms.ChoiceField(choices=my_choices)
或者你可以在my_choices
里面使用你喜欢的任何逻辑。
24
我经常在构造函数里动态设置选项:
class MyForm(BaseForm):
afield = forms.ChoiceField(choices=INITIAL_CHOICES)
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['afield'].choices = my_computed_choices