Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Model Fields Radio Button

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

like image 503
Thameem Avatar asked Sep 19 '16 06:09

Thameem


2 Answers

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

 gender = forms.ChoiceField(choices=GENDER_CHOICES, widget=forms.RadioSelect())
like image 107
Sagar Avatar answered Sep 22 '22 06:09

Sagar


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}
like image 42
mb_atx Avatar answered Sep 22 '22 06:09

mb_atx