Django - Check variables in POST/GET request

When a form is submitted, I wanna get the value of a key (variable) which is in the POST/GET data. For example:

myvalue = request.POST['mykey']

But if for some reason, the POST/GET data does not contains that data ('mykey': 'myvalue'). In this case, I have to check if the key 'mykey' is sent in POST/GET data and check if that key is not empty:

if 'mykey' in request.POST.keys() and request.POST['mykey']:
      myvalue = request.POST['mykey']

There is a Python method available on any Python dictionary names get(). get() lets you ask for the value of a particular key and specify a default to fallback on if the key doesn't exist. And, POST and GET are dictionaries.

myvalue = request.POST.get('mykey', '')

That get() method will save me (and you) so much time!


Post a Comment