2010-09-13 113 views
19

我有一個窗體,我用它來構建queryeset過濾器。表單從數據庫中提取項目狀態選項。不過,我想添加額外的選項,例如「所有現場促銷」 ......所以後來選擇框中將類似於:將其他選項添加到Django窗體選擇部件

  • 所有促銷活動*
  • 所有現場促銷*
  • 草案
  • 提交
  • 接受
  • 報道
  • 經過
  • 所有複合劑ED促銷*
  • 關閉
  • 取消

這裏的「*」都是我要新增和其他來自數據庫。

這可能嗎?

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'})) 

回答

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 

您還需要做些什麼形式的clean()方法來對付那些額外的選項,並與他們妥善處理巧妙。

相關問題