简体   繁体   English

如何更改特定 Django 管理员 Model 中的时区?

[英]How to change the timezone in the particular Django admin Model?

I want to change the timezone just within the one Particular Model in Django admin, how can I do that?我想在 Django 管理员中的一个特定 Model 内更改时区,我该怎么做?

As Django saves time in the database in UTC, what I want is to display the value in a particular timezone, just for one model.由于 Django 在 UTC 数据库中节省时间,我想要的是在特定时区显示值,仅针对一个 model。 Not for the whole project.不适用于整个项目。

For example I have a model:例如我有一个 model:

class Student(models.Models)
    created_at = models.DateTimeField()    

When I open Django Admin for this model, I want to see the time in a particular timezone (let's say ETC) but let the Django save time in UTC.当我为此 model 打开 Django Admin 时,我想查看特定时区的时间(比如说 ETC),但让 Django 节省时间。

so I have figured out the solution: To accomplish what I wanted to accomplish I had to made changes in the ModelAdmin class.所以我找到了解决方案:为了完成我想要完成的任务,我必须在ModelAdmin class 中进行更改。

    class StudentAdmin(Admin.ModelAdmin):
        list_display = [..., "created_at_etc", ...]
        def add_view(self, request, form_url='', extra_context=None):
            timezone.activate("US/Eastern")
            return super(ActivityAdmin, self).add_view(
                request,
                form_url,
                extra_context
            )

        def change_view(self, request, object_id, form_url='', extra_context=None):
            timezone.activate("US/Eastern")
            return super(ActivityAdmin, self).change_view(
                request,
                object_id,
                form_url,
                extra_context
          )

        def get_time(self, time):
            import pytz
            fmt = '%Y-%m-%d %H:%M:%S %Z'
            tz = pytz.timezone("US/Eastern")
            dt = time.astimezone(tz)
            return dt.strftime(fmt)

        def created_at_etc(self, student):
            return self.get_time(student.created_at)

        created_at_etc.short_description = "Created At"
    

You can activate a particular timezone in django admin by using您可以使用 django 管理员激活特定时区

from django.utils import timezone
timezone.activate("US/Eastern")

With this you can change the timezone within a context you want to.有了这个,您可以在您想要的上下文中更改时区。 As I am doing the same in the add_view , change_view .正如我在add_viewchange_view中做的一样。

First I overrided the add_view method that will let us create the Student object in the particular timezone.首先,我重写了add_view方法,它可以让我们在特定时区创建Student object。 Second I Overrided the change_view so that we can edit the already existing Student in the particular timezone.其次,我覆盖了change_view ,以便我们可以编辑特定时区中已经存在的Student Third I created created_at_etc it will display the date with respect to the particular timezone.第三,我创建了created_at_etc它将显示相对于特定时区的日期。

For more information you can use This Article .有关更多信息,您可以使用这篇文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM