Thwe Thwe - 7 days ago 5
Python Question

How to use forms.ChoiceField() inside ModelForm?

I want to show a dropdownlist in my form by using the ModelForm. My code added below-

from django import forms
from django.forms import ModelForm

class CreateUserForm(ModelForm):
class Meta:
model = User
fields = ['name', 'age']
AGE_CHOICES = (('10', '15', '20', '25', '26', '27', '28'))
age = forms.ChoiceField(
widget=forms.Select(choices=AGE_CHOICES)
)


It's not showing dropdownlist in the form. Also, I want "Select" selected as default with empty value. How can I achieve that?

Thanks in advance!

Answer

Modified your code.Try this :

from django import forms
from django.forms import ModelForm

class CreateUserForm(ModelForm):
    class Meta:
        model = User
        fields = ('name', 'age','grade')
        AGE_CHOICES = (
                ('', 'Select an age'),
                ('10', '10'), #First one is the value of select option and second is the displayed value in option
                ('15', '15'),
                ('20', '20'),
                ('25', '25'),
                ('26', '26'),
                ('27', '27'),
                ('28', '28'),
                )
         widgets = {
            'grade': forms.Select(choices=AGE_CHOICES,attrs={'class': 'form-control'}),
        }