In my admin.py file I am trying to display a time as the logged in users timezone. 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?
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 . 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.