Adding a Time Zone setting to your Django app
I'm currently working with a friend of mine on a Django app for Amazon sellers to automatically reprice their product listings. One of the features of the app is to show the price change history of their listings. Since they would want to see the timestamp of when the change occurred, we added a setting for them to set their Time Zone so they won't have to do time adjustments in their head.
We store all date/time data in the database in UTC. This is the default setting in Django (USE_TZ = True). Based on the user's Time Zone setting, we then use timezone.activate() in a middleware to make adjustments to the date/time before the template is rendered.
For the form field, we just used the pytz.common_timezones data to populate the choices.
# forms.py class ProfileForm(forms.Form): ... timezone = forms.ChoiceField( label=_('Time Zone'), choices=[(t, t) for t in pytz.common_timezones] )
The choices will look something like this:
Here's what our middleware looks like. It calls timezone.activate() to set the timezone on each request if the user is authenticated and make sure it's deactivated if not.
# middleware.py from django.utils import timezone import pytz class TimezoneMiddleware(object): def process_request(self, request): if request.user.is_authenticated(): timezone.activate(pytz.timezone(request.user.profile.timezone)) else: timezone.deactivate()
Now the user can keep changing his/her timezone setting to change the display while still storing all date/time records in UTC in the database.
Europe/London
Asia/Bangkok
Tags: howto, python, django, tech, software development