How do I stop my code from executing when a variable is None? I have tried many things. Here is my current incarnation:
post_body = request.POST
auth_user_id = post_body.get("auth_user_id", None)
if auth_user_id is not None:
print(auth_user_id)
search_user = SearchUser.objects.get(user_id=auth_user_id)
Right now this code dies on the last line with this error:
ValueError: invalid literal for int() with base 10: 'None'
And this:
print(auth_user_id)
Shows me "None".
So what is going on? How do I stop the code on None?
Obviously what you get here is the literal string 'None'
, not the None
object - note how the error messages differ, when passing None
you get a TypeError
, when passing 'None'
you get a ValueError:
# py2.7
>>> int(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string or a number, not 'NoneType'
>>> int('None')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'None'
# py3
>>> int(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
>>> int('None')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'None'
Your problem comes from the HTTP request body (since it's a POST) containing the literal string 'None'
for the "auth_user_id" key. Note that using a Django Form with proper validation would avoid the problem.