问题
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