[Django]-Add additional options to Django form select widget

30👍

You won’t be able to use a ModelChoiceField for that. You’ll need to revert to a standard ChoiceField, and create the options list manually in the form’s __init__ method. Something like:

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

You’ll also need to do something clever in the form’s clean() method to catch those extra options and deal with them appropriately.

Leave a comment