Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django: how to change values for nullbooleanfield in a modelform?

In the docs, the nullbooleanfield is represented as a <select> box with "Unknown", "Yes" and "No" choices. How can I change the values of select to some other more meaningful texts and map it back to the yes,no and unknown values in my modelform?

For example I have yes_no_required = models.NullBooleanField() and I would like to have 'yes I acknowledge this', 'no, I do not like this' and 'I do not know now' mapping to yes, no and required accordingly.

like image 933
goh Avatar asked Sep 02 '11 04:09

goh


People also ask

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What is null boolean field in Django?

NullBooleanField in Django Forms is a select field which stores either True or False. It is used for taking boolean inputs from the user. The default widget for this input is NullBooleanSelect. It normalizes to: A Python True or False value.

What is ModelForm in Django?

Django ModelForm is a class that is used to directly convert a model into a Django form. If you're building a database-driven app, chances are you'll have forms that map closely to Django models. For example, a User Registration model and form would have the same quality and quantity of model fields and form fields.


1 Answers

I spent half an hour putting together a demo just to prove to myself this works:

CHOICES = (
    (None, "I do not know now"),
    (True, "Yes I acknowledge this"),
    (False, "No, I do not like this")
)

class Demo(models.Model):
    yes_no_required = models.NullBooleanField(choices = CHOICES)

class DemoForm(forms.ModelForm):
    class Meta:
        model = Demo

I looked in the Django source code. Everything can accept a choices array. Obviously, for some of those that doesn't make sense, but it's possible.

like image 160
Elf Sternberg Avatar answered Oct 11 '22 12:10

Elf Sternberg