djangodjango-usersdjango-profiles

django profies and request.user - error


I'm getting the following error:

'AnonymousUser' object has no attribute 'get_profile'

after I added the following middleware, and try to log on to my site without having logged on before:

class TimezoneMiddleware(object):
    def process_request(self, request):
        try:
            driver = request.user.get_profile()
            timezone.activate(driver.timezone)
        except ObjectDoesNotExist:
            timezone.activate('UTC')

In the traceback, the error occurs at the first line of the try statement.

Thanks in advance for the help!


Solution

  • For non-logged in users, request.user is AnonymousUser instance, which does not contain get_profile. We could check whether an request.user has been logged in and protect logic for logged-in users by if request.user.is_authenticated():

    def process_request(self, request):
        if request.user.is_authenticated(): 
            try:
                driver = request.user.get_profile()
                timezone.activate(driver.timezone)
            except ObjectDoesNotExist:
                timezone.activate('UTC')