django profies和request.user - 错误

时间:2012-04-12 14:29:33

标签: django django-users django-profiles

我收到以下错误:

  

'AnonymousUser'对象没有属性'get_profile'

我添加了以下中间件后,尝试登录我的网站而未登录:

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

在回溯中,错误发生在try语句的第一行。

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

对于未登录的用户,request.userAnonymousUser个实例,不包含get_profile。我们可以检查request.user是否已登录并通过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')

答案 1 :(得分:0)

request.user.get_profile()可能会引发一个AttributeError,你应该尝试以下

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