Django DateField 的日历只显示月份和年份?
在 django 管理面板中,我目前有一个 DateField,显示一个漂亮的 Javascript 日历,用于输入日期。但是,我只对月份和年份感兴趣。所以我想知道是否可以让日历只显示月份和年份。 (如果您可以限制其使用,以便不能输入将来的日期,则可以获得额外的奖励分。)有人
提出了类似的问题,但没有回答,此处。
In the django admin panel I currently have a DateField showing a nice Javascript calendar for inputting dates. However, I am only interested in the Month and Year. So I was wondering if it was possible to have the calendar only show the months and year. (Extra brownie points if you can restrict its usage so that no dates in the future can be entered.)
A similar question was asked, but not answered, here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单(也是最正确的,因为您只关心月份和年份)要做的事情是将模型字段分为两个字段:月份和年份。并存储它。
因此,
您可以
:您可以在
clean()
方法中实现限制未来几年甚至未来几个月(年/月组合)所需的任何逻辑。编辑:我在上面的括号中说最正确,因为您确实没有要存储的日期。您必须决定存储所选月/年的第一天、最后一天或任意一天。
第二次编辑:就用于选择一年中的一个月的javascript而言,有是这个(请参阅该页面中的“月份选择日历”示例)。 可以将 JavaScript 添加到 Django 的管理页面 并使用它,但正如我之前的编辑中所述,您必须选择一天来处理。
The easiest (most correct also, since you only care about month and year) thing to do is to break the model field into two fields: month and year. And store that instead.
So instead of having:
You would have:
And you can implement whatever logic you need to restrict future years or even future months (Year/Month combinations) in the
clean()
method.Edit: I say most correct in parenthesis above because you really don't have a date to store. You would have to decide to store the first, or the last, or some arbitrary day of the month/year selected.
Second Edit: As far as javascript for picking a month of a year goes, there is this (see "Month-select calendar" example in that page). It is possible to add javascript to an admin page in Django and use that, but you would - as said in my previous edit - have to choose a day to deal with.