1

I am trying to use the SplitDateTimeWidget but want it to accept date in day - month - year format.

from django.forms.widgets import SplitDateTimeWidget

class EventForm(forms.ModelForm):
    class Meta:
        model = Event
        widgets = {'start': SplitDateTimeWidget(date_format='%d/%m/%Y')}

The SplitDateTimeWidget accepts a date_format argument, which I expect to be used to validate the date input but it isn't.

The default widget is correctly replaced but it ignores the date_format and insists on validating against the default month - day - year.

I also tried setting the DATE_FORMAT and DATE_INPUT_FORMATS settings with no luck.

Thanks for any help.

4

3 回答 3

7

这对我有用:

class EventForm(forms.ModelForm):

    start = SplitDateTimeField(input_date_formats=['%d/%m/%Y'],
                               input_time_formats=['%H:%M'], 
                               widget=SplitDateTimeWidget(date_format='%d/%m/%Y',
                                                          time_format='%H:%M'),
                               )

    class Meta:
        model = Event
于 2013-01-07T16:47:02.413 回答
1

小部件日期格式仅负责输出,与验证无关。重要的是字段类型,在 SplitDateTimeField 的情况下,它使用 DateField 和 TimeField ,它们是使用 input_date_formats 参数实例化的。

所以答案是:

class EventForm(forms.ModelForm):
    class Meta:
        model = Event
        widgets = {'start': SplitDateTimeWidget(date_format='%d/%m/%Y')}

    start = SplitDateTimeField(input_date_formats='d/m/Y',
                               input_time_formats='<whatever, or skip it>')

注意 input_date_formats 是 Django 格式,http ://docs.djangoproject.com/en/dev/ref/templates/builtins/#date

于 2011-10-06T14:46:13.567 回答
1

I had the same problem, trying to make the date part of SplitDateTimeField accept dates in the format '%d/%m/%Y'.

The solution above by Marat did not work for me(including the correction to it by omat)

I have finally solved the problem by overriding the default list of datetime input formats in settings.py:

DATETIME_INPUT_FORMATS = ('%d/%m/%Y %I:%M', '%Y-%m-%d %H:%M', '%Y-%m-%d',
    '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M', '%m/%d/%Y',
    '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M', '%m/%d/%y')

I added the desired format as the first in the list so it will take precedence over the others.

From Django documentation: "Formats will be tried in order, using the first valid"

于 2012-07-04T18:09:38.357 回答