Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 394
Thwe Avatar asked Nov 30 '16 10:11

Thwe


People also ask

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is the difference between form and ModelForm in Django?

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.

What is ChoiceField in Django?

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.

What is form Is_valid () in Django?

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.


1 Answers

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'}),
        }
like image 101
Prakhar Trivedi Avatar answered Sep 29 '22 07:09

Prakhar Trivedi