Skip to content

Instantly share code, notes, and snippets.

@aamishbaloch
Last active August 2, 2017 18:00
Show Gist options
  • Save aamishbaloch/ee972d333f7231b394526611c5985698 to your computer and use it in GitHub Desktop.
Save aamishbaloch/ee972d333f7231b394526611c5985698 to your computer and use it in GitHub Desktop.
Accepting Boolean Value in Params in Django (Python)

Accepting Boolean Value in Params in Django (Python)

There are cases in which we have to receive a boolean value in params to fill up an object. I have came through an idea of doing this, following utility method will help you doing this:

def str2bool(value):
    """
    convert string to bool
    """
    if value:
        return value.lower() in ("true",)
    else:
        return False

In your view: (Usage)

is_active = str2bool(self.request.query_params.get('active', 'true'))

You can have these kind of utility methods in your project to use them effectively. Kudos!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment