Setting Django admin display times to local time?

前端 未结 4 2196
天命终不由人
天命终不由人 2021-02-14 14:16

When I see dates and times in the admin, they are displayed in UTC. I\'d like for them to be displayed in my local timezone. I checked the TIME_ZONE setting in the

4条回答
  •  有刺的猬
    2021-02-14 14:19

    In Django:

    The default time zone is the time zone defined by the TIME_ZONE setting.

    The current time zone is the time zone that’s used for rendering.

    so you should set the "current time zone" use:

    django.utils.timezone.activate(timezone)

    You can activate it in a middleware(don't forger to register it to MIDDLEWARE in settings.py):

    import pytz    
    from django.utils import timezone
    
    class TimezoneMiddleware:
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            timezone.activate(pytz.timezone('Asia/Shanghai')
            return self.get_response(request)
    

    This is only a simple hardcode. you can making a form to select tzinfo, store it in user's profile and load it to user session, read the tzinfo from the session in the middleware.

    The official documentation has a related description: https://docs.djangoproject.com/en/3.0/topics/i18n/timezones/#selecting-the-current-time-zone

    Reference:

    https://groups.google.com/forum/#!topic/django-developers/E4aiv3O6vGo

提交回复
热议问题