仅在 django admin 中显示年份,YearField 而不是 DateField? [英] Only showing year in django admin, a YearField instead of DateField?

查看:16
本文介绍了仅在 django admin 中显示年份,YearField 而不是 DateField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型需要存储出生年份.我正在使用 django 管理员.使用它的人每天都会填写大量的人,并且 DateField() 显示太多(对日/月不感兴趣).

I've got a model where I need to store birth year. I'm using django admin. The person using this will be filling out loads of people every day, and DateField() shows too much (not interested in the day/month).

这是一个展示它现在的样机模型:

This is a mockup model showing how it is now:

class Person(models.Model):
  name = models.CharField(max_length=256)
  born = models.IntegerField(default=lambda: date.today().year - 17)

如您所见,大多数人都是 17 岁,所以我将他们的出生年份作为默认值.

As you can see, most of the people is 17 years old, so I'm getting their birth year as default.

我可以做得更好吗?如何从 DateField 中创建 YearField?如果制作一个 YearField,我什至可以制作一些简单的标签",比如那个日期的现在".(当然,一个专门的 BornYearField 会有 1989、1990、1991 和其他常见年份的简单按钮)

Can I do this better? How can I make a YearField out of the DateField? If making a YearField I can maybe even make some "easy tags" like the "now" that date has. (Of course, a specialized BornYearField would have easy buttons for 1989, 1990, 1991 and other common years)

推荐答案

我找到了 这个解决方案 我认为可以非常优雅地解决整个问题(不是我的代码):

I found this solution which solves the whole thing quite elegantly I think (not my code):

import datetime
YEAR_CHOICES = []
for r in range(1980, (datetime.datetime.now().year+1)):
    YEAR_CHOICES.append((r,r))

year = models.IntegerField(_('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)

编辑范围开始以扩展列表:-)

Edit the range start to extend the list :-)

这篇关于仅在 django admin 中显示年份,YearField 而不是 DateField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆