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.
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With