Django验证日期&表格中的时间 [英] Django Validate Date & Time in Forms
问题描述
我有一个视图,可以在表单上验证日期和时间,以确保日期和时间没有过去.日期和时间是两个单独的字段.它可以工作,但是我知道它的错误处理方式,并且应该在Django Forms中验证日期和时间.
I have a view where I validate date and time on form submit making sure the date + time are not past. Date and Time are two separate fields. It works, but I know its wrong way of doing it and the date+time should be validated in Django Forms.
这是在我的view.py
(可能操作方式不正确,但可行)
(Probably not done the right way but it works)
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表单中具有类似上面的内容:
now my goal is to have something like the above in Django forms:
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 ,感谢他的工作以及对我的耐心!
Thanks to all for the help especially xyres for his work and for being patient with me!
推荐答案
我将最后一次回答.代替执行def clean_my_date(...)
,请执行以下操作:
I'll try to answer one last time. Instead of doing def clean_my_date(...)
, do this:
def clean_my_time(self):
# rest of your code remains same
如果上述解决方案不起作用,请尝试此答案.
If the above solution doesn't work, try this answer.
更新
由于上述代码有效,我觉得我应该尝试解释原因和方式.
Since the above code worked, I feel I should try and explain why and how.
让我们看看表单中字段的顺序
Let's look at the order of fields in your form
fields = ['my_date', 'my_time', ...]
因此,您可以看到my_time
字段位于之后 my_date
字段.因此,当您的代码就像
As, you can see my_time
field comes after my_date
field. So, when your code was like
def clean_my_date(self)
窗体的clean()
方法被调用,它返回一个名为cleaned_data
的字典对象.此cleaned_data
字典具有表单最多 my_date
字段中的所有键即字段. my_date
之后的任何字段都不会在cleaned_data
中.因为my_time
字段在my_date
字段之后,所以它不在cleaned_data
中.这就是为什么您得到KeyError
.
the clean()
method of your form gets called and it returns a dictionary object called cleaned_data
. This cleaned_data
dict has all the keys i.e. fields of your form upto my_date
field. Any field that is after my_date
won't be in cleaned_data
. As, my_time
field is after my_date
field, it was not in cleaned_data
. That is why you got a KeyError
.
将代码更改为
def clean_my_time(self)
clean()
方法返回cleaned_data
,其中所有字段 up my_time
.由于my_date
在my_time
之前,因此它在cleaned_data
中.因此,没有错误.
the clean()
method returned cleaned_data
with all the fields upto my_time
. As my_date
comes before my_time
, it is, therefore, present in cleaned_data
. Hence, no error.
因此,这取决于表单字段的顺序.如果要一起验证两个字段,请按顺序在后面的字段的clean_my_field(self)
方法中进行验证. JérômeThiard 发布的答案也是一个很好的选择.
So it depends on the order of your form fields. If you want to validate two fields together, do it in the clean_my_field(self)
method of the field that comes later in order. The answer posted by Jérôme Thiard is also a good alternative.
这篇关于Django验证日期&表格中的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!