本文介绍了表单无法验证,因为date字段不是有效的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
表单无法验证,因为日期字段不是有效的格式,任何人都可以帮助我。
Form is not validating because of date field is not a valid format can any one help me.
USE_I18N = True
USE_L10N = True
USE_TZ = True
API = 'Apache-HttpClient'
ACCEPTABLE_FORMATS = ['%Y-%m-%d', # '2006-10-25'
'%d-%m-%Y', # '25-10-2006'
'%d/%m/%Y', # '25/10/2006'
'%d/%m/%y'] # '25/10/06'
models.py
models.py
class SaveTrip(models.Model):
"""storing user saving trips
"""
user = models.ForeignKey(User)
From = models.CharField(max_length=32)
to = models.CharField(max_length=32)
from_date = models.DateField(auto_now=False, auto_now_add=False)
to_date = models.DateField(auto_now=False, auto_now_add=False)
choice = models.CharField(max_length=32, null=True, blank=True)
class Meta:
verbose_name = "User Saved Trips"
def get_trip(self):
return "%s -> %s" % (self.From, self.to)
def __unicode__(self): # __str__ on Python 3
return self.get_trip()
Forms.py
Forms.py
class SaveTripForm(forms.Form):
From = forms.CharField(max_length=32)
to = forms.CharField(max_length=32)
from_date = forms.DateField(input_formats=ACCEPTABLE_FORMATS)
to_date = forms.DateField(input_formats=ACCEPTABLE_FORMATS)
choice = forms.CharField(max_length=32, required=False)
def clean(self):
cleaned_data = self.cleaned_data
From = cleaned_data.get("From")
to = cleaned_data.get("to")
from_date = cleaned_data.get("from_date")
to_date = cleaned_data.get("to_date")
choice = cleaned_data.get("choice")
return cleaned_data
shell
shell
python manage.py shell
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> a = {u'From':[u'Bangalore'], u'userid':[u'50'], u'choice':[u'(4,)'], u'to':[u'Goa'], u'from_date':[u'2016-10-20'], u'to_date':[u'2016-10-23']}
>>> from uprofile.forms import SaveTripForm
>>> abc = SaveTripForm(a)
>>> abc.is_valid()
False
>>> abc.errors
{'from_date': [u'Enter a valid date.'], 'to_date': [u'Enter a valid date.']}
>>> abc.cleaned_data
{'to': u"[u'Goa']", 'From': u"[u'Bangalore']", 'choice': u"[u'(4,)']"}
>>>
推荐答案
实际上, request.POST
数据。
表单无法通过LIST中的帖子数据值进行验证。
对于这个问题,我们可以这样实现
abc = SaveTripForm(a.dict())
python manage.py shell
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> a = {u'From':[u'Bangalore'], u'userid':[u'50'], u'choice':[u'(4,)'], u'to':[u'Goa'], u'from_date':[u'2016-10-20'], u'to_date':[u'2016-10-23']}
>>> from uprofile.forms import SaveTripForm
>>> abc = SaveTripForm(a.dict())
>>> abc.is_valid()
True
>>> abc.errors
{}
>>>
这篇关于表单无法验证,因为date字段不是有效的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!