3

视图.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.

4

2 回答 2

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

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

干杯

于 2013-07-05T13:33:15.263 回答
1

SettingsForm.__init__date_format的只是'1''0'。但是你应该得到真正的格式。此外,您应该从而不是date_formatcleaned_datainit args 获取:

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
于 2013-07-08T14:05:09.707 回答