Django DateField 的日历只显示月份和年份?

发布于 2024-08-19 21:10:43 字数 290 浏览 3 评论 0原文

在 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 技术交流群。

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

发布评论

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

评论(1

情深缘浅 2024-08-26 21:10:43

最简单(也是最正确的,因为您只关心月份和年份)要做的事情是将模型字段分为两个字段:月份和年份。并存储它。

因此,

class Blah(models.Model):
    ...
    your_date = models.DateField()

您可以

class Blah(models.Model):
    MONTH_CHOICES=((1,"January"), (2,"February"), ...)
    ...
    your_year = models.IntegerField()
    your_month = models.IntegerField(choices=MONTH_CHOICES)

:您可以在 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:

class Blah(models.Model):
    ...
    your_date = models.DateField()

You would have:

class Blah(models.Model):
    MONTH_CHOICES=((1,"January"), (2,"February"), ...)
    ...
    your_year = models.IntegerField()
    your_month = models.IntegerField(choices=MONTH_CHOICES)

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.

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