ObjectDoesNotExist not catching a DoesNotExist exception

Viewed 3536

I'm trying to catch a DoesNotExist exception, and inspecting the code where the exception is thrown is difficult. I can't reach the line that throws it in pdb, and in the debug trace there's no information on what object is throwing the exception, as it is contained under an instance variable so the django trace doesn't show what it's value is.

I have read the docs at https://docs.djangoproject.com/en/1.11/ref/exceptions/#objectdoesnotexist and this question at Catching Any DoesNotExist Error. Both of these indicate that to catch any DoesNotExist exception, one simply imports ObjectDoesNotExist and that covers all of them. It is not in my case. The exception is not caught in my except ObjectDoesNotExist block.

Code:

from django.core.exceptions import ObjectDoesNotExist

def check_permission(user):
    """function checks whether the user is in the list of allowed groups"""
    for option in ALLOWED: # list of groups, constant
        try:
            if user.groups.get().name == option:
                return True
        except ObjectDoesNotExist:
            pass
        else:
            pass
    return False

The trace reads:

File 
".../lib/python3.6/site-packages/django/db/models/query.py", line 379, in get self.model._meta.object_name

django.contrib.auth.models.DoesNotExist: Group matching query does not exist.

Which gets thrown from the line in my code:

if user.groups.get().name == option

attempting to access django.contrib.auth.models.DoesNotExist simply returns an

AttributeError: model 'django.contrib.auth.models' has no attribute 'DoesNotExist'

How do I catch this? Sometimes users will not have any groups and even if the site is designed for that to never happen, it still makes me nervous having breakable code here.

edit: python 3.6.2 django 1.11

full trace:

Traceback (most recent call last):
  File ".../lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
  File ".../lib/python3.6/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
  File ".../lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
  File ".../lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File ".../lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 23, in _wrapped_view
return view_func(request, *args, **kwargs)
  File ".../lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
  File ".../lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
  File "/Users/Mark/Desktop/Professional/FSC/water/WATER/sharedClasses.py", line 116, in get
return self.permission_denied_page(request, plans)
  File "/Users/Mark/Desktop/Professional/FSC/water/WATER/sharedClasses.py", line 68, in permission_denied_page
their_acccount = user.groups.get().name
  File ".../lib/python3.6/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
  File ".../lib/python3.6/site-packages/django/db/models/query.py", line 379, in get
self.model._meta.object_name
django.contrib.auth.models.DoesNotExist: Group matching query does not exist.
1 Answers

You should import Group and catch like this:'

from django.contrib.auth.models import Group

try:
    // your code
except Group.DoesNotExist:
   // to handle

BTW, why don't you write your method like following in much optimized way:

def check_permission(user):
   """return true if the user is in options, false if not"""
   if user.groups.filter(name__in=ALLOWED).exists():
      return True
   else:
      return False
Related