Django 模型形式如何从 Booleanfield 输出 select Yes/No
Django model form how to output select Yes/No from Booleanfield
我正在尝试对布尔字段进行 yes/no 选择。默认小部件是复选框输入。但是,如果我用 Select 覆盖默认小部件,我会得到:
NameError: Select is not defined
我认为这可能是因为我需要设置 Yes/No 以关联布尔字段中的布尔值,但不确定应该如何完成?
型号:
class User(models.Model):
online_account = models.BooleanField()
表格:
class AccountForm(forms.ModelForm):
class Meta:
model = User
fields = ('online_account')
labels = {
'online_account': 'Do you have an online account',
}
widgets = {'online_account': Select()}
我发现(并使用 Django 1.9.6 测试)this gist。它应该可以解决问题:
from django import forms
class Form(forms.Form):
field = forms.TypedChoiceField(coerce=lambda x: x =='True',
choices=((False, 'No'), (True, 'Yes')))
只需在模板的布尔字段中设置选项
from django.utils.translation import gettext_lazy as _
CHOICES_BOOLEANO_SIM_NAO = (
(True, _('Sim')),
(False, _('Não'))
)
class modelo(models.Model):
"""Model definition for LoteModalidadeEvento."""
# TODO: Define fields here
e_bool_field= models.BooleanField(verbose_name=_('Este é um campo booleano'), **choices**=CHOICES_BOOLEANO_SIM_NAO)
我正在尝试对布尔字段进行 yes/no 选择。默认小部件是复选框输入。但是,如果我用 Select 覆盖默认小部件,我会得到:
NameError: Select is not defined
我认为这可能是因为我需要设置 Yes/No 以关联布尔字段中的布尔值,但不确定应该如何完成?
型号:
class User(models.Model):
online_account = models.BooleanField()
表格:
class AccountForm(forms.ModelForm):
class Meta:
model = User
fields = ('online_account')
labels = {
'online_account': 'Do you have an online account',
}
widgets = {'online_account': Select()}
我发现(并使用 Django 1.9.6 测试)this gist。它应该可以解决问题:
from django import forms
class Form(forms.Form):
field = forms.TypedChoiceField(coerce=lambda x: x =='True',
choices=((False, 'No'), (True, 'Yes')))
只需在模板的布尔字段中设置选项
from django.utils.translation import gettext_lazy as _
CHOICES_BOOLEANO_SIM_NAO = (
(True, _('Sim')),
(False, _('Não'))
)
class modelo(models.Model):
"""Model definition for LoteModalidadeEvento."""
# TODO: Define fields here
e_bool_field= models.BooleanField(verbose_name=_('Este é um campo booleano'), **choices**=CHOICES_BOOLEANO_SIM_NAO)