Django:如何将 DateField 设置为仅接受“今天”和“今天”未来日期

发布于 2024-10-16 16:54:42 字数 226 浏览 2 评论 0原文

我一直在寻找方法将 Django 表单设置为仅接受今天或未来几天的日期。我目前在前端有一个 jQuery 日期选择器,但这里是模型表单的表单字段。

感谢您的帮助,非常感谢。

date = forms.DateField(
    label=_("What day?"),
    widget=forms.TextInput(),
    required=True)

I have been looking for ways to set my Django form to only accept dates that are today or days in the future. I currently have a jQuery datepicker on the frontend, but here is the form field to a modelform.

Thanks for the help, much appreciated.

date = forms.DateField(
    label=_("What day?"),
    widget=forms.TextInput(),
    required=True)

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

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

发布评论

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

评论(4

依 靠 2024-10-23 16:54:43

您可以在表单中添加 clean() 方法以确保日期不是过去的日期。

import datetime

class MyForm(forms.Form):
    date = forms.DateField(...)

    def clean_date(self):
        date = self.cleaned_data['date']
        if date < datetime.date.today():
            raise forms.ValidationError("The date cannot be in the past!")
        return date

请参阅http://docs.djangoproject.com/en/ dev/ref/forms/validation/#cleaning-a-specific-field-attribute

You could add a clean() method in your form to ensure that the date is not in the past.

import datetime

class MyForm(forms.Form):
    date = forms.DateField(...)

    def clean_date(self):
        date = self.cleaned_data['date']
        if date < datetime.date.today():
            raise forms.ValidationError("The date cannot be in the past!")
        return date

See http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute

硪扪都還晓 2024-10-23 16:54:43

另一个有用的解决方案是使用 validators 关键字参数将验证与字段联系起来。这是保持表单代码清晰并允许重用验证逻辑的便捷方法。例如

def present_or_future_date(value):
    if value < datetime.date.today():
        raise forms.ValidationError("The date cannot be in the past!")
    return value

class MyForm(forms.Form):
    date = forms.DateField(...
                           validators=[present_or_future_date])

Another useful solution is to tie validation to fields using the validators keyword argument. This is a handy way of keeping your Form code clear and enabling reuse of validation logic. For e.g

def present_or_future_date(value):
    if value < datetime.date.today():
        raise forms.ValidationError("The date cannot be in the past!")
    return value

class MyForm(forms.Form):
    date = forms.DateField(...
                           validators=[present_or_future_date])
时光磨忆 2024-10-23 16:54:43

发现 MinValueValidator 也非常适合日期。

import datetime
from django.core.validators import MinValueValidator
from django.db import models

...

some_date = models.DateField(validators=[MinValueValidator(datetime.date.today)])

Found out MinValueValidator works perfectly for dates as well.

import datetime
from django.core.validators import MinValueValidator
from django.db import models

...

some_date = models.DateField(validators=[MinValueValidator(datetime.date.today)])
忘年祭陌 2024-10-23 16:54:43

如果您使用的是 Django 1.2+ 并且您的模型将始终强制执行此规则,您还可以查看 模型验证。优点是任何基于模型的模型都会自动使用此验证。

If you are using Django 1.2+ and your model will always force this rule, you can also take a look at model validation. The advantage will be that any modelform based on the model will use this validation automatically.

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