[Django]-How to set a default TZ for django admin portal only?

3👍

A simple approach would be to create a middleware that sets the current timezone to EST for URLs in the admin domain. Something like:

from django.utils.deprecation import MiddlewareMixin  # needed since Django 2.0
from django.utils.timezone import activate

class AdminTimezoneMiddleware(MiddlewareMixin): 
    def process_request(self, request):
        if request.path.startswith("/admin"):
            activate(pytz.timezone("EST"))

(Of course, hardcoding the URL like this isn’t very DRY, but you get the idea.)

3👍

Django has a new middleware system since Kevin’s answer.

This should work in 1.9, 1.10, 1.11, 2.0

import pytz
from django.utils.timezone import activate


class AdminTimezoneMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(self.process_request(request))
        return response

    @staticmethod
    def process_request(request):
        if request.path.startswith("/admin"):
            activate(pytz.timezone("EST"))
        return request

Leave a comment