Django日期格式问题

时间:2013-06-19 10:06:02

标签: django django-models django-forms django-templates django-views

views.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))

forms.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上,日期的值会以某种方式更改并保存到数据库中,如下所示:如果给定日期是07/06/2013( 2013年6月7日),它将在2013年6月6日(2013年7月6日)保存在数据库中。因此,不保存所需的正确日期。

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

2 个答案:

答案 0 :(得分:1)

试试这个,

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))

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

干杯

答案 1 :(得分:1)

SettingsForm.__init__ date_format '1'只是'0'date_format。但你应该得到真正的格式。此外,您应该从cleaned_data获取class SettingsForm(forms.ModelForm): date_format = forms.ChoiceField(widget=forms.RadioSelect(), choices=DATE_FORMAT, initial='0') manual_date = forms.Date.... def clean(self, *args, **kwargs): super(SettingsForm, self).clean(*args, **kwargs) cleaned_data = self.cleaned_data date_format = cleaned_data['date_format'] for (num, candidate_format) in DATE_FORMAT: if num == date_format: actual_date_format = candidate_format break else: raise ...ValidationError('unsupported choice!') # self.cleaned_data['manual_date'] already contains value parsed by "default" date_formats. So we are using raw value instead of it: field = self.fields['manual_date'] field.input_formats = (actual_date_format, ) raw_value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix('manual_date')) value = field.clean(raw_value) cleaned_data['manual_date'] = value return cleaned_data ,而不是从init args:

获取
{{1}}