[Django]-RelatedObjectDoesNotExist error inspite of using if statement

5πŸ‘

βœ…

I guess you constructed a model that looks similar to:

class UserLocation(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # ...

Contrary to popular belief, a one-to-one field does not mean that the referenced model (here User) always has a UserLocation object. A OneToOneField actually is a ForeignKey field with a unique=True constraint (and some extra logic such that the reverse relation is not userlocation_set, but userlocation). So it means that two UserLocations can never refer to the same User object.

It is thus possible that there is no user.userlocation for some user, and in case the attribute is called, unfortunately it returns not None, but raises an error (there have been tickets to request that it returns None, but probably it will not be implemented in the (near) future, because of backwards compatibility).

So you should check with a try–catch–except:

from django.core.exceptions import ObjectDoesNotExist

class Homepage(TemplateView):
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super(Homepage, self).get_context_data(**kwargs)
        context['event_list'] = Event.objects.all()
        if self.request.user.is_authenticated()
            try:
                my_location = self.request.user.userlocation
            except ObjectDoesNotExist:
                # ... hande case where the location does not exists
            else:
                print("The location is {}".format(my_location))
        return context

7πŸ‘

Use an extra condition to your if clause which checks for an existence of userlocation attribute by using Python’s hasattr() method

Try this

class Homepage(TemplateView):
    template_name = 'home.html'

    def get_context_data(self, **kwargs):
        context = super(Homepage, self).get_context_data(**kwargs)
        context['event_list'] = Event.objects.all()
        if self.request.user.is_authenticated() and \
                hasattr(self.request.user, 'userlocation') and \
                self.request.user.userlocation:
            print("The code reached here ")
        return context

Reference
Django check if a related object exists error: RelatedObjectDoesNotExist

πŸ‘€JPG

-1πŸ‘

the User class doesn’t have userlocation variable.
use a custom user class inherited from User

πŸ‘€MH314K

Leave a comment