[英]How to set choices in dynamic with Django choicefield?
I want to set choices in dynamic.我想动态设置选择。
I used __set_choices method but, when request method is POST, is_valid method always return False.我使用了 __set_choices 方法,但是当请求方法是 POST 时,is_valid 方法总是返回 False。
if request.method=='POST':
_form = MyForm(request.POST)
if _form.is_valid():
#something to do
I often set the choices dynamicly in the constructor:我经常在构造函数中动态设置选项:
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
The key is to realise that choices
can be any iterable:关键是要意识到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)
Or whatever logic you like inside my_choices
.或者你在my_choices
中喜欢的任何逻辑。
In a view you could do the following在一个视图中,您可以执行以下操作
--views.py --views.py
lstChoices = _getMyChoices()
form.fields['myChoiceField'].choices = lstChoices
where lstChoices is list of dynamically generated tuples for your choices.其中 lstChoices 是供您选择的动态生成的元组列表。
Use the constructor to set dynamic choices as shown below:使用构造函数设置动态选择,如下所示:
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
In addition, I recommend to add the empty label '("", "---------")' to dynamic choices so that the dynamic choices works properly as the default behavior of the select box in Django .另外,我建议将空标签 '("", "---------")'添加到动态选择中,以便动态选择作为Django中选择框的默认行为正常工作。
与 maersu 的解决方案类似,但如果您有一个 ModelForm,其中一个模型具有一个 ForeignKey 到另一个模型,您可能希望分配给该字段的查询集而不是选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.