[Django]-What is the best way to have all the timezones as choices for a Django model?

8👍

If Django allowed choices to accept callables you could simply pass a lambda function. But since it doesn’t (yet), you should be able to simply define the choices list within your model class and use the zip function to dynamically generate the tuples. For example:

import pytz

class MyModel(models.Model):
    TIMEZONE_CHOICES = zip(pytz.all_timezones, pytz.all_timezones)

    timezone = models.CharField(max_length=255, default='UTC', choices=TIMEZONE_CHOICES)

The only issue I can see is that if a timezone is removed from the tz database in the future, the select box would be empty when you try to edit such a record.

👤Selcuk

Leave a comment