N
N
nik90192020-08-05 01:14:34
Django
nik9019, 2020-08-05 01:14:34

How to pass True or False value from form to models.BooleanField()?

Can you please tell me how to pass the True or False value from the form to the database.

The form field value is status = forms.BooleanField(required=False).
Line in model - status = models.BooleanField()

Form (without some attributes):

class CreateForm(forms.Form):
    ORDER_CHOICES =( #...какой-то список
    )
    data = forms.DateField(widget=forms.DateInput(attrs={'type': 'date'}), required=True)
    status = forms.BooleanField(required=False)    
    time = forms.TimeField(widget=forms.TimeInput(attrs={'type': 'time'}), required=True)
    order_type = forms.ChoiceField(choices = ORDER_CHOICES, widget=forms.RadioSelect(), required=True)
    name = forms.CharField(max_length=60, required=False)
    count = forms.IntegerField(required=False, widget=forms.TextInput(attrs={'value': '0', 'type':'number'}))
    comment = forms.CharField(widget=forms.Textarea, required=False)


DB model:
class Order(models.Model):
    data = models.DateField()
    status = models.BooleanField()
    time = models.TimeField(null=True)
    order_type = models.CharField(max_length=20)
    name = models.CharField(max_length=60, null=True)
    count = models.IntegerField(null=True)
    comment = models.CharField(max_length=60, null=True)


When trying to pass a value using the POST method, the following error occurs:
Exception Type: ValidationError
Exception Value: ['“on” value must be either True or False.']

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew, 2020-08-05
@deepblack

The template should have something similar to this:

<input checked="checked" type="checkbox" name="status" value="True" id="id_status" />

value="True" you have “on” value

N
nik9019, 2020-08-05
@nik9019

Now there is not enough time to figure out how to make the checkbox immediately return True or False, and not 'on', so I did the following in the view (maybe it will help someone):

if request.method == "POST":
        orders = Order()
        orders.data = request.POST.get("data")
        orders.time = request.POST.get("time")
        st = request.POST.get("status")
        if st == 'on':
            st = True
        else:
            st = False
        orders.status = st
        #какой-то код дальше...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question