Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model form how to output select Yes/No from Booleanfield

I'm trying to have a yes/no selection on a booleanfield. The default widget is checkboxinput. However if I override the default widget with Select I get a: NameError: Select is not defined

I think this may be because I need to setup Yes/No to correlate to the boolean values in the booleanfield, but not sure how this should be done?

Model:

class User(models.Model):
    online_account = models.BooleanField()

Form:

class AccountForm(forms.ModelForm):

    class Meta:
        model = User
        fields = ('online_account')
        labels = {
            'online_account': 'Do you have an online account',
        }
        widgets = {'online_account': Select()}
like image 423
Yunti Avatar asked Mar 13 '23 11:03

Yunti


2 Answers

I found (and tested with Django 1.9.6) this gist. It should do the trick:

from django import forms

class Form(forms.Form):
    field = forms.TypedChoiceField(coerce=lambda x: x =='True', 
                                   choices=((False, 'No'), (True, 'Yes')))
like image 95
Paolo Avatar answered Apr 24 '23 06:04

Paolo


Just set the choices in the template's boolean field

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)
like image 21
Max Silva Avatar answered Apr 24 '23 05:04

Max Silva