models.py
class Trainee(models.Model):
TraineeID = models.AutoField(primary_key=True)
Name = models.CharField(max_length=50)
Course = models.CharField(max_length=40)
BatchNo = models.CharField(max_length=15)
Gender = models.CharField(max_length=10)
DateofBirth = models.CharField(max_length=30)
ContactNo = models.CharField(max_length=20)
ContactAddress = models.CharField(max_length=80)
EmailAddress = models.EmailField()
class Meta():
db_table = "Trainee"
forms.py
class TraineeForm(forms.ModelForm):
class Meta():
model = Trainee
GENDER_CHOICES = [('M', 'Male'), ('F', 'Female'), ('O', 'Other')]
Gender = forms.ChoiceField(widget=forms.RadioSelect, choices=GENDER_CHOICES )
fields = ("__all__")
html page
<div >
<label > Gender: </label>
<div >
{{form.Gender}}
</div>
</div>
i am using radioselect for the first time in django. I looked to multiple dicussions on how to use it. I think i have done everything correctly. But in my page the gender does to come as a radio select but rather a normal input field does anyone know why? Any help will be appreciated. enter image description here
CodePudding user response:
Your field should be specified in the ModelForm
class, so:
class TraineeForm(forms.ModelForm):
GENDER_CHOICES = [('M', 'Male'), ('F', 'Female'), ('O', 'Other')]
Gender = forms.ChoiceField(
widget=forms.RadioSelect, choices=GENDER_CHOICES
)
class Meta:
model = Trainee
fields = '__all__'
It however makes more sense to specify the options:
class Trainee(models.Model):
GENDER_CHOICES = [('M', 'Male'), ('F', 'Female'), ('O', 'Other')]
trainee_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
course = models.CharField(max_length=40)
batch_no = models.CharField(max_length=15)
gender = models.CharField(max_length=10, choices=GENDER_CHOICES)
date_of_birth = models.CharField(max_length=30)
contact_no = models.CharField(max_length=20)
contact_address = models.CharField(max_length=80)
email_address = models.EmailField()
class Meta:
db_table = 'Trainee'
and then specify the widget in the form:
class TraineeForm(forms.ModelForm):
class Meta:
model = Trainee
widgets = {'gender': forms.RadioSelect}
fields = '__all__'