Michael Smith
Michael Smith

Reputation: 3447

How do I retrieve a boolean value from my form and do a comparison in a view in Django?

Currently I am retrieving a value like this in my view:

is_service = request.POST.get('is_service', '')

I then want to check if this value is false and if it is to do something. Currently I have

if is_service == 0 : 
    Do Something

I have tried a lot of other variations such as if is_service == False, etc.

What is the proper syntax to do this comparison in the view

Edit Here is my is_service definition:

class Service(models.Model):
    ...
    is_service = models.BooleanField(default=False)
    ...

Upvotes: 0

Views: 2873

Answers (1)

Scott Woodall
Scott Woodall

Reputation: 10676

You should use a Django form or modelForm and give the is_service field a boolean type. Django will normalize the string that is supplied by the user into the correct python type.

forms.py

class MyForm(forms.Form):
    is_service = forms.BooleanField()

views.py

def some_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)

        if form.is_valid():
            is_service = form.cleaned_data['is_service']

            if not is_service:
                # do something
    else:
        form = MyForm()

    return render(request, 'some_view.html', {'form': form})

some_view.html

<form action="/some_view/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>

Upvotes: 2

Related Questions