我想做一个日期 Select 器,不 Select 以前的日期使用Django.

class DateInput(forms.DateInput):
    input_type = 'date'

class TimeInput(forms.TimeInput):
    input_type = 'time'
"""class used for booking a time slot."""
class BookingForm(forms.ModelForm):
    class Meta:
        model = Booking
        fields = ['check_in_date', 'check_in_time', 'check_out_time',
                    'person', 'no_of_rooms']

        widgets = {
                    'check_in_date': DateInput(),
                    'check_in_time': TimeInput(),
                    'check_out_time': TimeInput(),
                }

    """Function to ensure that booking is done for future and check out is after check in"""
    def clean(self):
        cleaned_data = super().clean()
        normal_book_date = cleaned_data.get("check_in_date")
        normal_check_in = cleaned_data.get("check_in_time")
        normal_check_out_time = cleaned_data.get("check_out_time")
        str_check_in = str(normal_check_in)
        format = '%H:%M:%S'
        try:
            datetime.datetime.strptime(str_check_in, format).time()
        except Exception:
            raise ValidationError(
                _('Wrong time entered.'),
                code='Wrong time entered.',
            )


        # now is the date and time on which the user is booking.
        now = timezone.now()
        if (normal_book_date < now.date() or
            (normal_book_date == now.date() and
            normal_check_in < now.time())):
            raise ValidationError(
                "You can only book for future.", code='only book for future'
            )
        if normal_check_out_time <= normal_check_in:
            raise ValidationError(
                "Check out should be after check in.", code='check out after check in'
            )

上面的代码是在forms.py文件中编写的.如您所见,我制作了一个日期 Select 器,但问题是用户可以 Select 任何日期,但我希望他只 Select 当前或future 的日期.也许,这可以使用JavaScript或Bootstrap来完成,但我想知道我们可以在Django中完成吗?

推荐答案

您可以为date输入类型指定min attribute [mdn-doc]:

from django.utils.timezone import now


class FutureDateInput(forms.DateInput):
    input_type = 'date'

    def get_context(self, name, value, attrs):
        attrs.setdefault('min', now().strftime('%Y-%m-%d'))
        return super().get_context(name, value, attrs)

您将需要在表单/模型中进行验证,因为这将仅限于客户端.

Django相关问答推荐

AttributeError:';ManyToOneRel&39;对象没有属性';attname';

Django-表单(ModelForm)中的数据不保存在现有数据库中

如何删除Docker上的django应用程序?

错误``Forbidden (403) CSRF 验证失败.请求中止.``` 当try 登录管理员时

错误404除主要应用程序外,HTML页面无法渲染的其他应用程序

在 Django 模板中分页时如何正确显示与其父模型字段关联的所有内联字段?

使用 Django 一次更新多条记录

Django:想要将一个空字段显示为空白而不是显示无

Django 从 url 保存图像并与 ImageField 连接

Django Blob 模型字段

Django:通过manage.py使用服务器和gunicorn等其他服务器之间的区别.哪个更好?

如何从 django 自定义中间件类返回 rest_framework.response 对象?

Django:在模型管理器中获取模型的表名?

模型 Django 中的 ID 字段

Django 登录到控制台

django post_save 更新信号

刷新时重新提交的django表单

如何在 django 2.0 admin 中使用 allow_tags?

Django - TypeError - save() 得到了一个意外的关键字参数force_insert

Python Django 的多线程