django profies and request.user - error

拈花ヽ惹草 提交于 2020-01-05 05:56:10

问题


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!


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/10125688/django-profies-and-request-user-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!