Ammar Yassir
Ammar Yassir

Reputation: 59

Listing a ChoiceField in django as Button

Is there a way for me to change the way ChoiceFields are represented in django from a drop down list to something like buttons with each having a different choice ?

Upvotes: 0

Views: 1492

Answers (1)

Jose Cherian
Jose Cherian

Reputation: 7737

If you just need to change the style, you can pass the css class as attribute. See the Docs

select_media = forms.ChoiceField(widget=forms.Select(
    attrs={'class': 'btn btn-primary'}),
    choices=MEDIA_CHOICES)

enter image description here

enter image description here

If you need finer customization, you can override the default widget templates and put whatever html you want.See the docs here. Below code is for Django 1.11

class CustomSelectWidget(forms.Select):
    template_name: 'yourapp/select.html'
    option_template_name =  'yourapp/select_option.html'

class CustomForm(forms.Form):
    MEDIA_CHOICES = (
        (1, 'DVD'),
        (2, 'VCD'),
        (3,'USB')
        )
    select_media = forms.ChoiceField(widget=CustomSelectWidget(
        attrs={'class': 'btn btn-primary'}),
        choices=MEDIA_CHOICES)

Upvotes: 4

Related Questions