Reputation: 71
I am new to Django and Python. I want to add a radio button in my form but it doesn't work.
forms.py:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.forms.widgets import RadioSelect
from choicebtn.models import myChoice
class myChoiceForm(UserCreationForm):
name=forms.CharField(max_length=55)
TYPE_SELECT = (('0', 'Female'),('1', 'male'),)
gender=forms.ChoiceField(widgets.RadioSelect(choices=TYPE_SELECT))
class Meta:
model = myChoice
fields = ['name','gender']
model.py:
from django.db import models
from django.forms.widgets import RadioSelect
from django.urls import reverse
class myChoice(models.Model):
name=models.CharField(max_length=55)
TYPE_SELECT = (('0', 'Female'),('1', 'male'),)
gender=models.CharField(max_length=11,choices=TYPE_SELECT)
This only shows dropdownlist and textbox. It doesn't show radio buttons. Please help me.
Upvotes: 6
Views: 9558
Reputation: 1
Try something like this:
CHOICES = [('M','Male'),('F','Female')]
Gender=forms.CharField(label='Gender', widget=forms.RadioSelect(choices=CHOICES))
Upvotes: 0
Reputation: 592
In models.py:
class myChoice(models.Model):
name = models.CharField(max_length=55)
TYPE_SELECT = (
('0', 'Female'),
('1', 'male'),
)
gender = models.CharField(max_length=11,choices=TYPE_SELECT)
In forms.py:
class myChoiceForm(ModelForm):
class Meta:
model = myChoice
fields = ['__all__']
widgets = {
'gender': forms.RadioSelect()
}
Upvotes: 10
Reputation: 149
You can try this:
gender = forms.ChoiceField(choices=TYPE_SELECT, widget=forms.RadioSelect())
Upvotes: 0
Reputation: 416
Correct way to use it.
1)models.py
from django import forms
class ExampleModel(models.Model):
field1 = forms.ChoiceField(widget=forms.RadioSelect)
2)forms.py
class ExampleForm(forms.Form):
field1 = forms.ChoiceField(required=True, widget=forms.RadioSelect(
attrs={'class': 'Radio'}), choices=(('apple','Apple'),('mango','Mango'),))
Upvotes: -1