Skip to main content
 首页 » 编程设计

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

2024年10月17日7Terrylee

我想使用 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) 
    ) 

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

提前致谢!

请您参考如下方法:

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

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'}), 
        }