如何在 ModelForm 中使用 forms.ChoiceField() ?

Thw*_*hwe 7 python django django-models django-forms python-2.7

我想使用 ModelForm 在表单中显示一个下拉列表。我的代码添加如下 -

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)
    )
Run Code Online (Sandbox Code Playgroud)

它没有在表单中显示下拉列表。另外,我希望将“选择”选择为默认值并设置为空。我怎样才能做到这一点?

提前致谢!

Pra*_*edi 10

修改你的代码。试试这个:

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'}),
        }
Run Code Online (Sandbox Code Playgroud)