向 Django 表单选择小部件添加其他选项 [英] Add additional options to Django form select widget
问题描述
我有一个用于构建查询集过滤器的表单.该表单从数据库中提取项目状态选项.但是,我想添加其他选项,例如所有实时促销"……因此选择框将如下所示:
I have a form which I use to construct a queryeset filter. The form pulls in the project status options from the database. However, I wanted to add additional options, for example "All live promotions" ... so the select box would then look something like:
- 所有促销活动 *
- 所有实时促销活动 *
- 草稿
- 已提交
- 接受
- 已举报
- 已检查
- 所有已完成的促销活动 *
- 关闭
- 已取消
这里的*"是我想添加的,其他的来自数据库.
Here the '*' are the ones I'd want to add and the others come from the database.
这可能吗?
class PromotionListFilterForm(forms.Form):
promotion_type = forms.ModelChoiceField(label="Promotion Type", queryset=models.PromotionType.objects.all(), widget=forms.Select(attrs={'class':'selector'}))
status = forms.ModelChoiceField(label="Status", queryset=models.WorkflowStatus.objects.all(), widget=forms.Select(attrs={'class':'selector'}))
...
retailer = forms.CharField(label="Retailer",widget=forms.TextInput(attrs={'class':'textbox'}))
推荐答案
您将无法为此使用 ModelChoiceField.您需要恢复到标准的 ChoiceField,并在表单的 __init__
方法中手动创建选项列表.类似的东西:
You won't be able to use a ModelChoiceField for that. You'll need to revert to a standard ChoiceField, and create the options list manually in the form's __init__
method. Something like:
class PromotionListFilterForm(forms.Form):
promotion_type = forms.ChoiceField(label="Promotion Type", choices=(),
widget=forms.Select(attrs={'class':'selector'}))
....
EXTRA_CHOICES = [
('AP', 'All Promotions'),
('LP', 'Live Promotions'),
('CP', 'Completed Promotions'),
]
def __init__(self, *args, **kwargs):
super(PromotionListFilterForm, self).__init__(*args, **kwargs)
choices = [(pt.id, unicode(pt)) for pt in PromotionType.objects.all()]
choices.extend(EXTRA_CHOICES)
self.fields['promotion_type'].choices = choices
您还需要在表单的 clean()
方法中做一些聪明的事情来捕捉这些额外的选项并适当地处理它们.
You'll also need to do something clever in the form's clean()
method to catch those extra options and deal with them appropriately.
这篇关于向 Django 表单选择小部件添加其他选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!