views:

978

answers:

3

Django has a DATE_FORMAT and a DATE_TIME_FORMAT options that allow us to choose which format to use when viewing dates, but doesn't apparently let me change the input format for the date when editing or adding in the Django Admin.

The default for the admin is: YYYY-MM-DD

But would be awesome to use: DD-MM-YYYY

Is this integrated in any case in i18n? Can this be changed without a custom model?

+1  A: 

Looks like this is not yet supported, as I understand it, so yes, you'll have to do some custom work for now.

Dominic Rodger
+1  A: 

You have to do this yourself for now, but it's quite easy to do with a custom form field class that sets the input_formats argument of DateField. This should do it:

class MyDateField(forms.DateField):
  def __init__(self, *args, **kwargs):
    kwargs.setdefault('input_formats', ("%d-%m-%Y",))
    super(MyDateField, self).__init__(*args, **kwargs)

Note that input_formats is a list, so you can specify multiple possibilities and it will try them in order when parsing user input.

Carl Meyer
I can apply this on my new forms, but, how can I override the default form field in the admin site?
Andor
A: 

Based on this idea I made new db.fields class EuDateField:

mydbfields.py

from django import forms
from django.forms.fields import DEFAULT_DATE_INPUT_FORMATS
from django.db import models

class EuDateFormField(forms.DateField):
    def __init__(self, *args, **kwargs):
        kwargs.update({'input_formats': ("%d.%m.%Y",)+DEFAULT_DATE_INPUT_FORMATS})
        super(EuDateFormField, self).__init__(*args, **kwargs)

class EuDateField(models.DateField):
    def formfield(self, **kwargs):
        kwargs.update({'form_class': EuDateFormField})
        return super(EuDateField, self).formfield(**kwargs)

Note that it adds my format (e.g. 31.12.2007) to existing "standard" django formats at first place.

Usage:

from mydbfields import EuDateField
class Person(models.Model):
    ...
    birthday   = EuDateField("Birthday", null=True, blank=True, help_text="")

In my case this renders good in admin, but most probably will in ModelForm too (haven't tried it).

My django version is:

>>> import django
>>> django.get_version()
u'1.1 alpha 1 SVN-10105'
trebor74hr