开发者

DateField & TimeField formatting with jQuery DatePicker & TimePicker

I have a form (2 fields) where the user selects/inputs a Date & Time using jQuery's DatePicker & TimePicker. The format's that come out are :

 01/05/2011
 11:00 PM开发者_JAVA技巧

The form will not submit, so I think there is a conflict with those formats and the DateField & TimeField I am using in my form class. Is this true? If so, what format do these inputs need to be?

Thanks!


You can read the validation code for these fields by looking at the Django source.

Looking in django/forms/fields.py, read the to_python() methods on the DateField and TimeField classes.

It looks to me like they both support a number of input types:

  • An instance of a datetime.datetime object
  • An instance of a datetime.date object
  • A string formatted according to the setting DATE_INPUT_FORMATS (or TIME_INPUT_FORMATS)

I think the last option is what you want. Checking in django/conf/global_settings.py, you can see the default values of these settings, which include a large range of strptime format strings. Here's the default DATE_INPUT_FORMATS:

'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
'%b %d %Y', '%b %d, %Y',            # 'Oct 25 2006', 'Oct 25, 2006'
'%d %b %Y', '%d %b, %Y',            # '25 Oct 2006', '25 Oct, 2006'
'%B %d %Y', '%B %d, %Y',            # 'October 25 2006', 'October 25, 2006'
'%d %B %Y', '%d %B, %Y',            # '25 October 2006', '25 October, 2006'

So, any date string formatted any of these ways should work (assuming your locale isn't set to something wacky -- each locale has locale-specific overrides for this field, and you should check the locale subdirectory for the locale you're working with).

There's similar logic for TIME_INPUT_FORMATS which by default are:

'%H:%M:%S',     # '14:30:59'
'%H:%M',        # '14:30'

So I suspect that's what's preventing your form from working, since your time has AM/PM.

You can set TIME_INPUT_FORMATS manually in your settings.py to a strptime format string that will work for what you want, which will probably be something like "%I:%M %p" (Note that you can't just use %r because it looks like it requires seconds). You might want to include the original values as well, just for possible compatibility with other things (like the Django admin interface).

I'm not that familiar with the jQuery date & time pickers -- maybe you can configure them to output the time in a format that's already supported by Django?


I have this setup running fine just using

LANGUAGE_CODE = 'fr-FR'

in my settings.py and using a language file for jQueryUI
this page has the full example of a jqueryUI language file

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜