[英]How to set choices in dynamic with Django choicefield?
我想動態設置選擇。
我使用了 __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
中喜歡的任何邏輯。
在一個視圖中,您可以執行以下操作
--views.py
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
另外,我建議將空標簽 '("", "---------")'添加到動態選擇中,以便動態選擇作為Django中選擇框的默認行為正常工作。
與 maersu 的解決方案類似,但如果您有一個 ModelForm,其中一個模型具有一個 ForeignKey 到另一個模型,您可能希望分配給該字段的查詢集而不是選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.