-1

Why doesn't None put in variable? I wrote in code like

def check(request):
    if len(request.POST.get('access_key')) >= 25:
        return HttpResponse('<h1>Hello</h1>')
    elif request.POST.get('access_key', None) == None:
        id_json = {}
        return JsonResponse(id_json, safe=False)
    else:
        return HttpResponse('<h1>Good</h1>')

Now I put anything to access_key in POSTMAN like enter image description here

I think in this case the program goes into elif request.POST.get('access_key', None) == None:,but now it goes into else:.

I really cannot understand why the null value is not recognized as None. I wrote print(type(request.POST.get('access_key'))) and blank is printed out.

I wanna make a system if no value is put, and the program should go into elif request.POST.get('access_key', None) == None:.

How should I fix this?

ezdazuzena
  • 6,120
  • 6
  • 41
  • 71
user8817477
  • 739
  • 1
  • 8
  • 12
  • Also, you should use `is` or `is not` when checking for `None`, not `==`/`!=`. `if x is None` or `if x is not None` – DeepSpace Nov 20 '17 at 08:50
  • 1
    `print(None)` wouldn't print a blank. Ergo, you the value is not equal to `None`. Just use `elif not request.POST.get('access_key'):`. – Martijn Pieters Nov 20 '17 at 08:59

2 Answers2

2

The return value of request.POST.get('access_key') is '', which is not None.

Try to check for elif not request.POST.get('foo'), this will catch both cases, because both, `` and None will evaluate to False. Actually, all three values ('', None, and False) as value will fulfill the if condition if not value:.

Have a look at this wiki page: https://en.wikipedia.org/wiki/Empty_string

In most programming languages, the empty string is distinct from a null reference (or null pointer) because a null reference does not point to any string at all..

And more precisely for Python: https://docs.python.org/2/library/constants.html

The sole value of types.NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function.

ezdazuzena
  • 6,120
  • 6
  • 41
  • 71
  • 1
    However it is important to note that both `''` and `None` evaluate to `False` in an `if` condition (ie when passed to `bool`) https://stackoverflow.com/a/39984051/1453822 – DeepSpace Nov 20 '17 at 08:53
  • 1
    The default value for the second argument to `.get()` is already `None`. `elif not request.POST.get('foo'):` suffices. – Martijn Pieters Nov 20 '17 at 08:59
1

your request.POST.get('access_key') is equal ''

so instead of

elif request.POST.get('access_key', None) == None:

try simple

elif not request.POST.get('access_key'):
Brown Bear
  • 19,655
  • 10
  • 58
  • 76