Django Model Fields Radio Button

21,350

Solution 1

Default widget for choice field is choice/selection list. you can change widget in form

 gender = forms.ChoiceField(choices=GENDER_CHOICES, widget=forms.RadioSelect())

Solution 2

This works for Django 2.1 and up

models.py keep unchanged

In admin.py

   from django.contrib import admin 

   class ProfileAdmin(admin.ModelAdmin):

   fields = (......, 'gender',...)

   radio_fields = {'gender': admin.VERTICAL}
Share:
21,350
Thameem
Author by

Thameem

Updated on July 09, 2022

Comments

  • Thameem
    Thameem almost 2 years

    how can i create a radio button using Django model fields

    #models.py
    
    GENDER_CHOICES = (
       ('M', Male),
       ('F', 'Female')
    )
    
    class Profile(models.Model):
         gender = models.CharField(choices=GENDER_CHOICES, max_length=128)
    

    the above field is rendering as a select field, But i want to make it as a radio button.

    If the question is not correct, somebody please correct the question