[英]How to access current user in admin.py
In my admin.py file I am trying to display a time as the logged in users timezone. 在我的admin.py文件中,我试图将时间显示为登录用户的时区。 If I have something like below how can I pass in the request also to access the request.user.userprofile so I can dynamically set the timezone?
如果我有类似下面的内容,我如何也可以传入请求以访问request.user.userprofile,以便可以动态设置时区?
class CapAdmin(admin.ModelAdmin):
...
list_display = ('time_clicked', 'source_name', 'link')
....
def time_clicked(self, instance):
local_tz = pytz.timezone('America/Chicago') # I want the user timezone here
local_dt = instance.click_time.replace(tzinfo=pytz.utc).astimezone(local_tz)
return mark_safe("{0}").format(local_tz.normalize(local_dt).strftime('%b %d, %Y, %I:%M %p'))
You don't have access to the user there. 您无权访问那里的用户。 But you don't need it;
但是你不需要它; you should be activating the timezone in middleware, as described in the docs .
您应该按照docs中的说明激活中间件中的时区。 Something like:
就像是:
class TimezoneMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.user.is_authenticated and request.user.timezone
tzname = request.user.timezone
timezone.activate(pytz.timezone(tzname))
else:
timezone.deactivate()
Add this to your middleware settings. 将此添加到您的中间件设置。 Now in your admin class you can do:
现在,在您的管理类中,您可以执行以下操作:
from django.utils.timezone import localtime
def time_clicked(self, instance):
return localtime(instance.time_clicked)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.