【问题标题】:How to use forms.ChoiceField() inside ModelForm?如何在 ModelForm 中使用 forms.ChoiceField()?
【发布时间】:2017-04-14 15:05:24
【问题描述】:

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

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

提前致谢!

【问题讨论】:

  • 字段不应该是元类的一部分,只需将其缩进到类级别
  • grade是User模型的一个字段吗,还是你把grade写错了age。?
  • 对不起,弄错了!已经更新了。谢谢

标签: python django python-2.7 django-models django-forms


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-05-20
    • 2016-12-28
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 2012-02-09
    • 2015-12-22
    相关资源
    最近更新 更多