向Django表单选择小部件添加其他选项
我有一个用于构造查询集过滤器的表单。表单从数据库中提取项目状态选项。但是,我想添加其他选项,例如“所有现场促销”。。。因此,选择框的外观如下所示:向Django表单选择小部件添加其他选项,django,django-forms,Django,Django Forms,我有一个用于构造查询集过滤器的表单。表单从数据库中提取项目状态选项。但是,我想添加其他选项,例如“所有现场促销”。。。因此,选择框的外观如下所示: class PromotionListFilterForm(forms.Form): promotion_type = forms.ChoiceField(label="Promotion Type", choices=(), widget=forms.Select
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
- 所有促销活动*
- 所有现场促销活动*
- 草稿
- 提交
- 接受
- 报告
- 检查
- 所有已完成的促销活动*
- 封闭的
- 取消
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,并在表单的
\uuuu init\uuu
方法中手动创建选项列表。比如:
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()
方法中进行一些巧妙的操作,以捕获这些额外的选项并适当地处理它们