Django: How to get American date format in a form?

1,071 views
Skip to first unread message

Houmie

unread,
Aug 13, 2012, 9:48:31 AM8/13/12
to django...@googlegroups.com

Hello everyone,

For some reason the American date format is not accepted in my form. I wonder if any Django developer from US could help me with this. I suspect the timezone in the settings also affect the date format, but I am not sure.

Settings:

TIME_ZONE = 'Europe/London'
LANGUAGE_CODE
= 'en-us'
USE_I18N
= True
USE_L10N
= True
USE_TZ
= True

ModelForm:

class CallsForm(ModelForm):    
   
class Meta:
        model
= Conversation  
        widgets
= {
                   
'contact_date': forms.DateInput(attrs={'placeholder': 'Add the date...', 'id': 'datepicker', 'class': 'placeholder_fix_css'}, format='%m/%d/%Y'),
                   
}

enter image description here

Any idea why the American Dateformat still isn't accepted?

Many Thanks,
Houman

houmie

unread,
Aug 13, 2012, 10:23:45 AM8/13/12
to django...@googlegroups.com
Ahhh finally now I know what is happening:

MIDDLEWARE_CLASSES = (
    ...
    'django.middleware.locale.LocaleMiddleware',
)

It seems as soon as the LocaleMiddleware is loaded, Django gets the settings frommy  browser session, Hence the dateformat is changed to European reflect my location. Clever.

Now that the date input is accepted in American dateformat.
Within the template I get Aug. 31, 2012, which is also correct.
However in the forms, once I try to modify the record I get 2012-08-31

That doesn't seem right. Sure I could use the field format, but isn't that hardcoded and bad practice?

How do you guys in US do that?

Thanks,
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/uuMUxpVhbx4J.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

Melvyn Sopacua

unread,
Aug 13, 2012, 12:20:57 PM8/13/12
to django...@googlegroups.com
On 13-8-2012 12:23, houmie wrote:

> However in the forms, once I try to modify the record I get 2012-08-31
>
> That doesn't seem right. Sure I could use the field format, but isn't
> that hardcoded and bad practice?

Setting localize=True on the form field (form, not model) should do the
trick. If you're using a ModelForm the not so obvious way is to provide
a formfield_callback to the ModelForm construction, which looks
something like this:

def formfield_callback(field, **kwargs) :
return field.formfield(localize=True, **kwargs)

Looking at django.forms.models.modelform_factory will shed some light on
this.
And of course:
<https://docs.djangoproject.com/en/1.4/ref/forms/fields/#localize>
--
Melvyn Sopacua

houmie

unread,
Aug 13, 2012, 12:47:57 PM8/13/12
to django...@googlegroups.com
Thanks Melvyn,

I have tried this:

def contact_date_callback(self, field, **kwargs) :
return field.contact_date(localize=True, **kwargs)

But the date still shows as 2012-08-13

note, that Aptana Studio 3.0 complained that I put `self` first.

Nonetheless neither version works.

Any other idea? :(

Carlos Palol

unread,
Aug 13, 2012, 1:46:26 PM8/13/12
to django...@googlegroups.com
Try configuring your form field directly, like this:

class CallsForm(ModelForm):
    contact_date = forms.DateField(
        localize=True,
        input_formats=['%m/%d/%Y'],
        widget=forms.DateInput(attrs={
            'placeholder'='Format is m/d/yyyy...',
        })
    )

   
    class Meta:
        model = Conversation

This combination of attributes input_formats and localize should make this field to use the m/d/y format for forms (always), while printing the value in the localized way (Aug. 31, 2012).

Cheers

Melvyn Sopacua

unread,
Aug 13, 2012, 1:49:01 PM8/13/12
to django...@googlegroups.com
On 13-8-2012 14:47, houmie wrote:
> Thanks Melvyn,
>
> I have tried this:
>
> def contact_date_callback(self, field, **kwargs) :
> return field.contact_date(localize=True, **kwargs)
>
> But the date still shows as 2012-08-13
>
> note, that Aptana Studio 3.0 complained that I put `self` first.
>
> Nonetheless neither version works.

It works, but it's not visible:
>>> from one.models import Person, localize_field
>>> from django.forms.models import modelform_factory
>>> FormClass = modelform_factory(Person, formfield_callback=localize_field)
>>> form = FormClass()
>>> form.fields['registered'].localize
True
>>> from django.utils.translation import activate
>>> activate('en-us')
>>> print form
...
<input type="text" name="registered" value="2012-08-13"
id="id_registered" />
...
>>> activate('nl_NL')
>>> print form
...
<input type="text" name="registered" value="13-08-2012"
id="id_registered" />
...

The reason is in django/conf/locale/en/formats.py. Localize uses the
first *_INPUT format available, which happens to be:
DATE_INPUT_FORMATS = (
'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006',
'10/25/06'

So if you want a different input format, you'll need to override this as
described at:
<https://docs.djangoproject.com/en/1.4/topics/i18n/formatting/#creating-custom-format-files>
--
Melvyn Sopacua

houmie

unread,
Aug 13, 2012, 1:54:47 PM8/13/12
to django...@googlegroups.com
Thanks Carlos,  Yes I could utilize the format field as you suggested and it would work fine but this is bad.

I will have customers in USA and also in Europe. Both would run from the same server, hence I need eventually enable the localization according to the user's locality.

MIDDLEWARE_CLASSES = (
    ...
    'django.middleware.locale.LocaleMiddleware',
)

So from then on the Americans can see their date in their format and Europeans in theirs.
If I hardcoded the format like this though, this would break it for one or the other group.  Django has to do it through the culture automatically.

I don't understand, it works for templates, inputformat for forms works as well, only the form-output is not working. So weird...I really am curios how the American Django users have setup their date fields in the ModelForm. :)   I think I have to wait til later today so they wake up and see the emails. :))

Thank you,
Houman
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/7MlUvieqzRUJ.

houmie

unread,
Aug 13, 2012, 2:16:36 PM8/13/12
to django...@googlegroups.com
Thanks Melvyn for the example.

Interesting you get the same problem with American date output as I. So
its on purpose to pick the first available input-format from formats.py.
Which is very odd if you ask me. I was expecting this to be culture
specific too.

Ok, let see how we can fix this. Thanks for the link, yes I could
override DATETIME_INPUT_FORMATS within a custom-formats.py

mysite/
formats/
__init__.py
en/
__init__.py
formats.py


But looking at this example, 'en/' is not good enough. British English
is also `en` but the date format is European. You know what I mean?
Again the culture seems to be forgotten :(
Unless I could define the path as en-GB/ and it would still be
recognized....

Melvyn Sopacua

unread,
Aug 13, 2012, 2:30:12 PM8/13/12
to django...@googlegroups.com
On 13-8-2012 16:16, houmie wrote:

> But looking at this example, 'en/' is not good enough. British English
> is also `en` but the date format is European. You know what I mean?
> Again the culture seems to be forgotten :(
> Unless I could define the path as en-GB/ and it would still be
> recognized....

django/conf/locale/en_GB/ exists.
The internationalization modules first look for specific then for the
less specific match if it doesn't exist.
--
Melvyn Sopacua

houmie

unread,
Aug 13, 2012, 3:40:11 PM8/13/12
to django...@googlegroups.com
This is brilliant. Thank you so much Melvyn. Now I can switch the
cultures between British and US without having to change any code. :)

I was also surprised to see that Django is using by default the military
(24h) time. From what I remember the Americans usually prefer 12 hours
AM/PM.

So I have overridden it like '%I:%M %p', and it works 11:15 PM within
the forms.

Its just a bit odd that templates show 11:15 p.m. Slight difference in
the formatting. Also the dates within templates are defined like Aug
13, 2012. Doesn't confirm with my definition in formats.py.
Are they stored somewhere else?

Melvyn Sopacua

unread,
Aug 13, 2012, 8:41:38 PM8/13/12
to django...@googlegroups.com
On 13-8-2012 17:40, houmie wrote:

> Its just a bit odd that templates show 11:15 p.m. Slight difference in
> the formatting. Also the dates within templates are defined like Aug
> 13, 2012. Doesn't confirm with my definition in formats.py.
> Are they stored somewhere else?

No, but you need the localize filter or tag:
<https://docs.djangoproject.com/en/1.4/topics/i18n/formatting/#controlling-localization-in-templates>


--
Melvyn Sopacua

Melvyn Sopacua

unread,
Aug 13, 2012, 8:52:35 PM8/13/12
to django...@googlegroups.com
Wait, if this is the same data from the model, then you need to change
the DATE_FORMAT. DATE_INPUT_FORMAT is for form fields, since the form
field needs to be able to change it back to a format that python's
datetime.date will understand. DATE_FORMAT is used for plain output.

--
Melvyn Sopacua

houmie

unread,
Aug 13, 2012, 11:28:12 PM8/13/12
to django...@googlegroups.com
Yes you are absolutely right about Date_Format and Time_Format.

But the Time_Format gives me trouble. By default it is defined as
TIME_FORMAT = 'P' and the output is p.m. (see two dots)

My TIME_INPUT_FORMATS = ('%I:%M %p',) produces PM (in capital case and
I prefer it this way)

I tried to change TIME_FORMAT = 'P' to TIME_FORMAT = '%p', but it breaks.

houmie

unread,
Aug 14, 2012, 11:47:37 AM8/14/12
to django...@googlegroups.com
I found here what I needed:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
There are shortcuts to customize the settings.

Thanks for your kind help Melvyn.

Regards,
Houman
Reply all
Reply to author
Forward
0 new messages