Django フォーム選択ウィジェットに追加オプションを追加する 質問する

Django フォーム選択ウィジェットに追加オプションを追加する 質問する

クエリセット フィルターを作成するために使用するフォームがあります。フォームは、データベースからプロジェクト ステータス オプションを取得します。ただし、たとえば「すべてのライブ プロモーション」などの追加オプションを追加したいので、選択ボックスは次のようになります。

  • すべてのプロモーション *
  • すべてのライブプロモーション *
  • 下書き
  • 提出済み
  • 承認済み
  • 報告
  • チェック済み
  • 完了したすべてのプロモーション *
  • 閉まっている
  • キャンセル

ここで、「*」は追加したいもので、その他はデータベースから取得されます。

これは可能ですか?

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

ベストアンサー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()メソッドで、これらの追加オプションをキャッチして適切に処理するための巧妙な操作を行う必要があります。

おすすめ記事