我想做一个日期 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中完成吗?