I was trying to catch a specific exception:
username = 'myuser'
try:
user = User.objects.get(username=username)
print(user)
except Exception as e:
if type(e)=='django.contrib.auth.models.User.DoesNotExist':
print('No such user')
print (type(e))
But instead of going into the if loop, I am getting:
<class 'django.contrib.auth.models.User.DoesNotExist'>
Why is this happening? How can I catch a specific exception?
type(e)does not return a string. Theifcondition should beif type(e) == django.contrib.auth.models.User.DoesNotExistor better,if isinstance(e, django.contrib.auth.models.User.DoesNotExist). But the correct overall solution would be JPG's answer