ChoiceField list in django as Button

Is there a way to change the way django displays ChoiceFields from a dropdown to something like buttons, each with a different choice?

0


source to share


1 answer


If you just need to change the style, you can pass the css class as an attribute. See 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 more customization, you can override the default widget templates and place whatever html you want. Check out the docs here . Below is the code 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)

      

+2


source







All Articles