[Django]-Checkboxes and Radio buttons in Django ModelForm

11๐Ÿ‘

โœ…

you can do something like this

CHOICES=[('item1','item 1'),
         ('item2','item 2')]
class OrderCreateForm(forms.ModelForm):
    postal_code = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())
    ....
class Meta:
    model = Order
    fields = ['first_name', 'last_name', 'email', 'address', 'postal_code', 'city']

similarly, you can do for the other field also

and for checkbox, you can define it as a BooleanFileld and you can use

{{ form.paid }}

in you template.

๐Ÿ‘คbadiya

2๐Ÿ‘

The form will be rendered with the field types you define in the model:

  • BooleanField is rendered as a checkbox, paid in your case.
  • ChoiceField can be rendered as radio buttons with the appropiate widget.

You can redefine the widgets in class OrderCreateForm:

CHOICES = [('option1','label 1'), ('option2','label 2')]
some_field = forms.ChoiceField(choices=CHOICES,widget=forms.RadioSelect())

๐Ÿ‘คXaviP

Leave a comment