I have a User
model with a timezone
field on it:
class User(AbstractBaseUser, PermissionsMixin):
timezone = models.CharField(
max_length=64,
choices=[(tz, tz) for tz in pytz.common_timezones],
default="UTC",
)
When viewed in Django admin, this creates a drop-down list of timezones, but only of the names. I would like to dynamically generate labels for this drop-down that add the offset as a prefix (eg +02:00
) and sort the list by that. I know I can create these by doing something like:
choices=[
(tz, display_with_offset(tz))
for tz in pytz.common_timezones
],
where display_with_offset
generates the required label, but I think this would only calculate it when the migrations are run and would ignore any daylight savings changes that happen throughout the year for some regions.
My admin file looks like this:
class MyUserAdmin(UserAdmin):
fieldsets = [
("Info", {"fields": ("timezone")}),
]
admin.site.register(models.User, MyUserAdmin)
Is there a way I can dynamically set the drop-down labels?
You can create a ModelForm and override the choices. For example:
class UserAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['timezone'].choices = [
(tz, display_with_offset(tz)) for tz in pytz.common_timezones
]
class Meta:
model = User
fields = '__all__'
class MyUserAdmin(UserAdmin):
fieldsets = [
("Info", {"fields": ("timezone")}),
]
form = UserAdminForm
More information can be found in documentation .
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.