forms.py
class SearchFilterForm(Form):
fromdate = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'dd/mm/yy','class':'datefield','readonly':'readonly'}))
todate = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'dd/mm/yy','class':'datefield','readonly':'readonly'}))
models.py
class Report(models.Model):
user = models.ForeignKey(User, null=False)
created_date_time = models.DateTimeField('Created')
sent_date_time = models.DateTimeField('Sent')
在数据库中,日期对象以这种格式YYYY-MM-DD HH:MM
保存,我在forms.py中使用格式为dd/mm/yyyy
。如果我使用yyyy-mm-dd格式,我没有收到任何错误因为我在表格中使用了dd / mm / yyyy格式,所以我得到了这个验证错误。我想知道如何处理这个问题。
答案 0 :(得分:5)
您应该在表单中使用DateField
并配置input_formats
以支持您要使用的格式:
ACCEPTABLE_FORMATS = ['%d-%m-%Y', # '25-10-2006'
'%d/%m/%Y', # '25/10/2006'
'%d/%m/%y'] # '25/10/06'
# Add your own at will, but be mindful of collisions.
class SearchFilterForm(Form):
fromdate = forms.DateField(input_formats=ACCEPTABLE_FORMATS)
todate = forms.DateField(input_formats=ACCEPTABLE_FORMATS)
See the docs了解更多信息!
更好的是,you can enable localization in your Django app,让django自动为您使用正确的格式!
# settings.py
USE_L10N = True
# forms.py
class SearchFilterForm(Form):
fromdate = forms.DateField(localize=True)
todate = forms.DateField(localize=True)