在 Django 管理站点中,如何更改时间字段的显示格式?

发布于 2024-12-01 12:02:52 字数 177 浏览 0 评论 0原文

我最近向我的网站添加了一个新模型,并且我使用 admin.py 文件来准确指定我希望它在管理网站中的显示方式。它工作得很好,但我不知道如何让我的日期字段之一在其显示格式中包含秒。我只看到像“Aug. 27, 2011, 12:12 pm”这样的值,而我想看到的是“Aug. 27, 2011, 12:12*:37* pm”

I recently added a new model to my site, and I'm using an admin.py file to specify exactly how I want it to appear in the admin site. It works great, but I can't figure out how to get one of my date fields to include seconds in it's display format. I'm only seeing values like "Aug. 27, 2011, 12:12 p.m." when what I want to be seeing is "Aug. 27, 2011, 12:12*:37* p.m."

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

热鲨 2024-12-08 12:02:52

四处挖掘我就结束了,但对我的应用程序应用了不同的方法。

更改 django admin 默认格式可以通过更改您想要的每种类型的 django 区域设置格式来完成。

将以下内容放在您的 admin.py 文件(或 settings.py)中,以更改 django 管理员的日期时间默认格式。

from django.conf.locale.es import formats as es_formats

es_formats.DATETIME_FORMAT = "d M Y H:i:s"

它将更改该文件(或整个站点,如果在设置中)上的 ModelAdmin 日期时间格式。

正如 @Alan Illing 在评论中指出的那样,它不会破坏管理日期时间过滤器和订单功能。

希望这对将来有所帮助


额外信息:

您可以为 django 中的每个可用语言环境更改它,这些语言环境有很多。

您可以使用此方法更改以下格式

from django.conf.locale.es import formats as es_formats

es_formats.DATETIME_FORMAT
es_formats.NUMBER_GROUPING
es_formats.DATETIME_INPUT_FORMATS  
es_formats.SHORT_DATETIME_FORMAT
es_formats.DATE_FORMAT             
es_formats.SHORT_DATE_FORMAT
es_formats.DATE_INPUT_FORMATS      
es_formats.THOUSAND_SEPARATOR
es_formats.DECIMAL_SEPARATOR       
es_formats.TIME_FORMAT
es_formats.FIRST_DAY_OF_WEEK       
es_formats.YEAR_MONTH_FORMAT
es_formats.MONTH_DAY_FORMAT

digging around I ended here but applied a different approach to my app.

Changing django admin default formats could be done changing the django locale formats for every type you want.

Put the following on your admin.py file (or settings.py) to change datetime default format at your django admin.

from django.conf.locale.es import formats as es_formats

es_formats.DATETIME_FORMAT = "d M Y H:i:s"

It will change the ModelAdmin's datetime formats on that file (or whole site if in settings).

It does not breaks admin datetime filters and order features as @Alan Illing has point out in comments .

hope this help in future


Extra info:

You can change it for every available locale in django, which are a lot.

You can change the following formats using this approach

from django.conf.locale.es import formats as es_formats

es_formats.DATETIME_FORMAT
es_formats.NUMBER_GROUPING
es_formats.DATETIME_INPUT_FORMATS  
es_formats.SHORT_DATETIME_FORMAT
es_formats.DATE_FORMAT             
es_formats.SHORT_DATE_FORMAT
es_formats.DATE_INPUT_FORMATS      
es_formats.THOUSAND_SEPARATOR
es_formats.DECIMAL_SEPARATOR       
es_formats.TIME_FORMAT
es_formats.FIRST_DAY_OF_WEEK       
es_formats.YEAR_MONTH_FORMAT
es_formats.MONTH_DAY_FORMAT
一片旧的回忆 2024-12-08 12:02:52

在 ModelAdmin 中尝试一下:

def time_seconds(self, obj):
    return obj.timefield.strftime("%d %b %Y %H:%M:%S")
time_seconds.admin_order_field = 'timefield'
time_seconds.short_description = 'Precise Time'    

list_display = ('id', 'time_seconds', )

当然,将“timefield”替换为模型中的适当字段,并在“list_display”中添加任何其他所需的字段。

Try this in the ModelAdmin:

def time_seconds(self, obj):
    return obj.timefield.strftime("%d %b %Y %H:%M:%S")
time_seconds.admin_order_field = 'timefield'
time_seconds.short_description = 'Precise Time'    

list_display = ('id', 'time_seconds', )

Replacing "timefield" with the appropriate field in your model, of course, and adding any other needed fields in "list_display".

一绘本一梦想 2024-12-08 12:02:52

如果您尝试过加布里埃尔的答案但不起作用,请尝试在 settings.py 中设置 USE_L10N = False,它对我有用。

请注意,如果 USE_L10N 设置为 True,则区域设置指定的格式具有更高的优先级,并且将被应用

参见:https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-DATETIME_FORMAT

If you've tried gabriel's answer but it did not work, try to set USE_L10N = False in settings.py, it works for me.

Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead

See: https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-DATETIME_FORMAT

奈何桥上唱咆哮 2024-12-08 12:02:52

接受的答案是正确的,但是我发现理解它的工作方式/原因有点令人困惑。下面是一个小例子,我希望它能更清楚地说明如何做到这一点。

Django 提供了几种在管理视图中显示“自定义”字段的方法。我更喜欢实现此行为的方法是在 ModelAdmin 类中定义一个自定义字段并显示该字段,而不是您想要的字段:

from django.contrib import admin
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()

class PersonAdmin(admin.ModelAdmin):
    @admin.display(description='Birthday')
    def admin_birthday(self, obj):
        return obj.birthday.strftime('%Y-%m-%d')

    list_display = ('name', 'admin_birthday')

请注意,而不是显示实际的 birthday 字段在 Person 模型中,我们将自定义字段 (admin_birthday) 定义为 PersonAdmin 中的方法,并通过将其添加到 PersonAdmin 中来显示该字段代码>list_display 属性。此外,admin.display() 装饰器修改 Django 在管理视图中显示此自定义字段的方式。使用这种方法,管理面板将显示姓名生日字段,但使用您首选的日期格式。

我更喜欢这种方法的原因是您将模型字段定义与管理面板中的显示方式分开。您可以在 Django 管理文档

The accepted answer is correct, however I found it a bit confusing to understand how/why it works. Below is a small example that I hope illustrates how to do this more clearly.

Django provides a few ways to display "custom" fields in your admin view. The way I prefer to achieve this behavior is to define a custom field in the ModelAdmin class and display that instead of your intended field:

from django.contrib import admin
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()

class PersonAdmin(admin.ModelAdmin):
    @admin.display(description='Birthday')
    def admin_birthday(self, obj):
        return obj.birthday.strftime('%Y-%m-%d')

    list_display = ('name', 'admin_birthday')

Notice that instead of displaying the actual birthday field from the Person model, we define a custom field (admin_birthday) as a method in the PersonAdmin and display that instead by adding it to the list_display attribute. Furthermore, the admin.display() decorator modifies how Django will display this custom field in the admin view. Using this approach, the admin panel will show the NAME and BIRTHDAY fields but using your preferred date formatting for the date.

The reason I prefer this approach is you keep the Model field definitions separate from how you display them in the admin panel. You can read more about alternative approaches in the Django admin documentation.

同尘 2024-12-08 12:02:52

这对我有用:

在 models.py 中:

class InvoiceValidateLog(models.Model):
    invoice = models.ForeignKey(SpvInvoice, on_delete=models.CASCADE)
    validated_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    status = models.BooleanField()
    modified_at = models.DateTimeField(auto_now=True)
    comment = models.TextField(null=True)

在 admin.py 中

from django.contrib import admin
from django.utils import timezone
from .models import InvoiceValidateLog

class InvoiceValidateLogAdmin(admin.ModelAdmin):
    list_display = ('invoice', 'validated_by', 'comment', 'status', 'formatted_modified_at')
    list_filter = ('validated_by__username', 'invoice__no')
    search_fields = ('invoice__no', 'validated_by__username')
    
    # Custom method to display datetime with seconds in local time
    def formatted_modified_at(self, obj):
        # Convert the 'modified_at' to the local time zone
        local_time = timezone.localtime(obj.modified_at)
        return local_time.strftime('%Y-%m-%d %H:%M:%S')
    
    # Preserve sorting on the actual 'modified_at' field
    formatted_modified_at.admin_order_field = 'modified_at'
    formatted_modified_at.short_description = 'Modified At'

admin.site.register(InvoicePayLog, InvoicePayLogAdmin)

This works for me:

In models.py:

class InvoiceValidateLog(models.Model):
    invoice = models.ForeignKey(SpvInvoice, on_delete=models.CASCADE)
    validated_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    status = models.BooleanField()
    modified_at = models.DateTimeField(auto_now=True)
    comment = models.TextField(null=True)

In admin.py

from django.contrib import admin
from django.utils import timezone
from .models import InvoiceValidateLog

class InvoiceValidateLogAdmin(admin.ModelAdmin):
    list_display = ('invoice', 'validated_by', 'comment', 'status', 'formatted_modified_at')
    list_filter = ('validated_by__username', 'invoice__no')
    search_fields = ('invoice__no', 'validated_by__username')
    
    # Custom method to display datetime with seconds in local time
    def formatted_modified_at(self, obj):
        # Convert the 'modified_at' to the local time zone
        local_time = timezone.localtime(obj.modified_at)
        return local_time.strftime('%Y-%m-%d %H:%M:%S')
    
    # Preserve sorting on the actual 'modified_at' field
    formatted_modified_at.admin_order_field = 'modified_at'
    formatted_modified_at.short_description = 'Modified At'

admin.site.register(InvoicePayLog, InvoicePayLogAdmin)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文