在我的admin.py文件中,我试图将时间显示为已登录用户的时区。如果下面有类似的内容,我如何也可以传递请求以访问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'))
答案 0 :(得分:0)
您无权访问该用户。但是你不需要它;您应该按照the docs中所述在中间件中激活时区。像这样:
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()
将此添加到您的中间件设置。现在,您可以在管理类中进行以下操作:
from django.utils.timezone import localtime
def time_clicked(self, instance):
return localtime(instance.time_clicked)