2

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

1
  • I can Catch the meaning of your question. can you please, explain what you try to achieve by using the BooleanFIeld ?. is it to update the product status for a vendor so when the product out of stock the status can be tracked ? Commented Jun 28, 2018 at 4:37

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

hi, thanks for the help, but this is not what I want, I really appreciate your help
@SulthonMaulanaArrasyid: then you probaby better update the question, and explain what you want in more detail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.