gpt4 book ai didi

Django 日期格式问题

转载 作者:行者123 更新时间:2023-12-02 02:01:04 24 4
gpt4 key购买 nike

View .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 用于将两种输入格式保存到一个表中。它为 %m/%d/%Y 格式保存一个 int 值“1”,为 %d/%m/%Y 格式保存一个“0”。

如果输入格式是%m/%d/%Y,那么在表单POST上,日期的值会以某种方式改变并保存到数据库中this:如果给定日期是 07/06/2013(2013 年 6 月 7 日),则它在数据库中保存为 06/07/2013(2013 年 7 月 6 日)。因此,没有保存所需的正确日期。

如果选择的格式是 %d/%m/%Y,它确实可以正常工作。

最佳答案

试试这个,

def calender(request):

""""""
settingsform = SettingsForm(instance=settings)

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)
if request.method == 'POST':
reportform = ReportDateTimeForm(request.POST, instance=report,date_format=date_format)
if reportform.is_valid():
report = reportform.save(commit=False)
report.user = request.user
report.save()
""""""
return render_to_response('calender.html',
{
'reportform': reportform,
'settings': settings,
'settingsform':settingsform
},
context_instance=RequestContext(request))

我对你的代码做了一些小改动,我想它会解决你的问题。

干杯

关于Django 日期格式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17188493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com