سؤال

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!

هل كانت مفيدة؟

المحلول

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')

نصائح أخرى

request.user.get_profile() probably raises an AttributeError, you should try the following

class TimezoneMiddleware(object):
    def process_request(self, request):
        try:
            driver = request.user.get_profile()
            timezone.activate(driver.timezone)
        except ObjectDoesNotExist, AttributeError:
            timezone.activate('UTC')
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top