alj*_*alj 19 django django-forms
我有一个表单,我用它来构建一个queryeset过滤器.表单从数据库中提取项目状态选项.但是,我想添加其他选项,例如"所有实时促销"......所以选择框看起来像是这样的:
这里'*'是我想要添加的,其他来自数据库.
这可能吗?
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'}))
Run Code Online (Sandbox Code Playgroud)
Dan*_*man 30
您将无法使用ModelChoiceField.您需要恢复到标准的ChoiceField,并在表单的__init__方法中手动创建选项列表.就像是:
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
Run Code Online (Sandbox Code Playgroud)
你还需要在表单的clean()方法中做一些聪明的事情来捕获那些额外的选项并适当地处理它们.
| 归档时间: |
|
| 查看次数: |
27985 次 |
| 最近记录: |