【问题标题】:Django model form how to output select Yes/No from BooleanfieldDjango模型表单如何从布尔字段输出选择是/否
【发布时间】:2016-01-28 15:05:54
【问题描述】:

我正在尝试在布尔字段上选择是/否。默认小部件是复选框输入。但是,如果我用 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 django-forms


    【解决方案1】:

    只需在模板的布尔字段中设置选择

    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)
    

    【讨论】:

      【解决方案2】:

      我找到了(并使用 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')))
      

      【讨论】:

        猜你喜欢
        • 2012-02-06
        • 2013-01-07
        • 1970-01-01
        • 2010-12-19
        • 2017-07-04
        • 2015-10-10
        • 1970-01-01
        • 1970-01-01
        • 2010-11-05
        相关资源
        最近更新 更多