2

表格.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'}))

模型.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 格式表单我收到此验证错误。我想知道如何处理。

4

1 回答 1

5

You should use a DateField in your form and configure input_formats to support the format you'd like to use:

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 for more!


Better yet, you can enable localization in your Django app, and let django use the correct format for you automatically!

# settings.py
USE_L10N = True

# forms.py
class SearchFilterForm(Form):    
    fromdate = forms.DateField(localize=True)
    todate = forms.DateField(localize=True)
于 2013-06-21T06:15:21.107 回答