gpt4 book ai didi

python - Django 验证表单中的日期和时间

转载 作者:行者123 更新时间:2023-12-03 16:17:02 25 4
gpt4 key购买 nike

我有一个 View ,我在表单提交时验证日期和时间,确保日期 + 时间没有过去。日期和时间是两个独立的字段。它有效,但我知道它的错误方式,并且应该在 Django Forms 中验证日期+时间。

这是我的 view.py
(可能没有以正确的方式完成,但它有效)

my_date = request.session['reservationdate'] #in "mm/dd/yyyy" format
my_time = request.session['reservationtime'] #in "hh:mm" format
my_date_time = (my_date + ' ' + my_time + ':00') #convert to "mm/dd/yyyy hh:mm:ss"
my_date_time = datetime.strptime(my_date_time, '%m/%d/%Y %H:%M:%S') #convert to valid datetime
if datetime.now() <= my_date_time:
#do this
else:
...

现在我的目标是在 Django 表单中有类似上面的内容:
class MyForm(forms.ModelForm):  

def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)

self.fields['my_date'].required = True
self.fields['my_time'].required = True
...

def clean_my_date(self):
my_date = self.cleaned_data['my_date']
my_time = self.cleaned_data['my_time']
my_date_time = (my_date + ' ' + my_time + ':00')
my_date_time = datetime.strptime(my_date_time, '%m/%d/%Y %H:%M:%S')
if datetime.now() <= my_date_time:
raise forms.ValidationError(u'Wrong Date!')
return my_date

class Meta:
model = MyModel
fields = ['my_date', 'my_time', ...]

编辑:

工作代码:
def clean_my_time(self):
my_date = self.cleaned_data['my_date']
my_time = self.cleaned_data['my_time']
my_date_time = ('%s %s' % (my_date, my_time))
my_date_time = datetime.strptime(my_date_time, '%Y-%m-%d %H:%M:%S')
if datetime.now() >= my_date_time:
raise forms.ValidationError(u'Wrong Date or Time! "%s"' % my_date_time)
return my_time

特别感谢大家的帮助 xyres 感谢他的工作和对我的耐心!

最佳答案

您正在尝试验证多个字段。 django 文档很好地涵盖了这一点,请参阅 https://docs.djangoproject.com/en/1.7/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other .

这项工作必须在 clean 中完成方法。
假设 django 1.7,你的代码可能看起来像

class MyForm(forms.ModelForm):  

def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)

self.fields['my_date'].required = True
self.fields['my_time'].required = True
...

def clean(self):
cleaned_data = super(MyForm, self).clean()
# here all fields have been validated individually,
# and so cleaned_data is fully populated
my_date = cleaned_data.get('my_date')
my_time = cleaned_data.get('my_time')
if my_date and my_time:
my_date_time = (my_date + ' ' + my_time + ':00')
my_date_time = datetime.strptime(my_date_time, '%m/%d/%Y %H:%M:%S')
if datetime.now() <= my_date_time:
msg = u"Wrong Date time !"
self.add_error('my_date', msg)
self.add_error('my_time', msg)
return cleaned_data

class Meta:
model = MyModel
fields = ['my_date', 'my_time', ...]

关于python - Django 验证表单中的日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27552780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com