【问题标题】:Add additional options to Django form select widget向 Django 表单选择小部件添加其他选项
【发布时间】:2011-04-11 15:44:37
【问题描述】:

我有一个用于构造查询集过滤器的表单。该表单从数据库中提取项目状态选项。但是,我想添加其他选项,例如“所有实时促销”......所以选择框看起来像:

  • 所有促销活动 *
  • 所有现场促销活动 *
  • 草稿
  • 已提交
  • 接受
  • 已举报
  • 已检查
  • 所有已完成的促销活动 *
  • 关闭
  • 已取消

这里的“*”是我要添加的,其他来自数据库。

这可能吗?

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

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    您将无法为此使用 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() 方法中做一些巧妙的事情来捕捉这些额外的选项并适当地处理它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多