只显示一年在django管理员,一年YearField而不是DateField? [英] Only showing year in django admin, a YearField instead of DateField?

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

问题描述

我有一个模型,我需要存储出生年份。我正在使用django管理员。使用这个的人每天都会填满人数,DateField()显示的太多了(对日/月不感兴趣)。



这是一个模型显示现在的模型:

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

如你所见,大多数人是17岁,所以我的出生年份是默认的。



我可以这样做吗更好?如何使YearField退出DateField?如果做一个YearField,我甚至可以制作一些像现在那样的简单的标签。 (当然,1989年,1990年,1991年和其他常年的专业BornYearField将有简单的按钮)

解决方案

一个href =https://groups.google.com/d/msg/django-users/al95x1TXFV4/7mCCWQE3jtAJ =noreferrer>这个解决方案解决了整个事情非常优雅我认为(不是我的代码):

  import datetime 
YEAR_CHOICES = []
为范围内的r(1980,(datetime .datetime.now()。year + 1)):
YEAR_CHOICES.append((r,r))

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

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


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)

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

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'), max_length=4, choices=YEAR_CHOICES, default=datetime.datetime.now().year)

Edit the range start to extend the list :-)

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

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