视图.py
def calender(request):
""""""
settingsform = SettingsForm(instance=settings)
if request.method == 'POST':
reportform = ReportDateTimeForm(request.POST, instance=report)
if reportform.is_valid():
report = reportform.save(commit=False)
report.user = request.user
report.save()
if settings and settings.date_format:
date_format = reportform.fields['manual_date'].input_formats[1]
createddate = report.created_date_time.strftime('%b %d %Y')
else:
date_format = reportform.fields['manual_date'].input_formats[0]
createddate = report.created_date_time.strftime('%d %b %Y')
date = report.manual_date.strftime(date_format)
""""""
return render_to_response('calender.html',
{
'reportform': reportform,
'settings': settings,
'settingsform':settingsform
},
context_instance=RequestContext(request))
表格.py
DATE_FORMAT = (
('0', ' dd / mm / yyyy'),
('1', 'mm / dd / yyyy'),
)
DATE_INPUT_FORMAT = ['%d/%m/%Y','%m/%d/%Y']
class ReportDateTimeForm(forms.ModelForm):
manual_date = forms.DateField(input_formats = DATE_INPUT_FORMAT,
widget=forms.DateInput(format = '%d/%m/%Y'))
class SettingsForm(forms.ModelForm):
date_format = forms.ChoiceField(widget=forms.RadioSelect(), choices=DATE_FORMAT, initial='0')
def __init__(self, *args, **kwargs):
# Get the date_format if present in parameters
date_format = None
if 'date_format' in kwargs:
date_format = kwargs.pop('date_format')
# Dynamically set input date format
super(ReportDateTimeForm, self).__init__(*args, **kwargs)
if date_format:
self.fields['manual_date'].input_formats = (date_format, )
SettingsForm 类用于将两种输入格式保存到一个表中。它为格式保存一个 int 值“1”,为该%m/%d/%Y
格式保存一个“0” %d/%m/%Y
。
如果输入格式是%m/%d/%Y
,那么在 form 上POST
,日期的值会以某种方式更改并保存到数据库中,如下所示:如果给定日期是 07/06/2013(2013 年 6 月 7 日),则将其保存在数据库中2013 年 6 月 7 日(2013 年 7 月 6 日)。因此,不保存所需的正确日期。
如果选择的格式是%d/%m/%Y
.