How to use boolean field in form - Python Django

I'm working on a Django blog, i want to use Boolean Field in Form

Here is my Code:

class CreateProductForm(forms.Form):
    name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}))
    content = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control', 'id': 'ck-editor-area'}))
    excerpt = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control', 'rows': '7'}), required=False)
    price = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Amount'}))
    status = forms.CharField(widget=forms.Select(choices=(('1', 'Active'),('0', 'Inactive'),), attrs={'class':'form-control'}))
    quantity = forms.CharField(widget=forms.NumberInput(attrs={'class':'form-control'}))

I want to change the Status field

status = forms.CharField(widget=forms.Select(choices=(('1', 'Active'),('0', 'Inactive'),), attrs={'class':'form-control'}))

with Boolean Field function (True or False)

What should i do? Thank you

Upvotes: 2

Views: 382

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

You can pick a certain value to represent True and False (by using strings), and then "coerce" with a function (for example through a lambda expression):

status = forms.TypedChoiceField(
    choices=((True, 'Active'), (False, 'Inactive')),
    coerce=lambda x: x == 'True',
)

We thus use the values True and False, and we later use coerce to cast the string representation back to a valid boolean.

Upvotes: 1

Related Questions