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!
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
The similarities are that they both generate sets of form inputs using widgets, and both validate data sent by the browser. The differences are that ModelForm gets its field definition from a specified model class, and also has methods that deal with saving of the underlying model to the database. Save this answer.
ChoiceField in Django Forms is a string field, for selecting a particular choice out of a list of available choices. It is used to implement State, Countries etc. like fields for which information is already defined and user has to choose one. It is used for taking text inputs from the user.
The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.
Modified your code.Try this :
from django import forms
from django.forms import ModelForm
class CreateUserForm(ModelForm):
class Meta:
model = User
fields = ('name', 'age')
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 = {
'age': forms.Select(choices=AGE_CHOICES,attrs={'class': 'form-control'}),
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With