我希望能够动态设置选项。
我使用了__set_choices方法,但是当请求方法为POST时,is_valid方法总是返回False。
if request.method=='POST':
_form = MyForm(request.POST)
if _form.is_valid():
#something to do
我希望能够动态设置选项。
我使用了__set_choices方法,但是当请求方法为POST时,is_valid方法总是返回False。
if request.method=='POST':
_form = MyForm(request.POST)
if _form.is_valid():
#something to do
我经常在构造函数中动态设置选项:
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
关键在于意识到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
中使用任何逻辑。
lstChoices = _getMyChoices()
form.fields['myChoiceField'].choices = lstChoices
其中lstChoices是动态生成的元组列表,用于你的选择。
class DateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Write the code here to set dynamic choices
self.fields['month'].choices = dynamic_choices
与maersu的解决方案类似,但如果您有一个包含对另一个模型的ForeignKey的模型的ModelForm,则可能希望将其分配给字段的查询集而不是选择。