views:

81

answers:

2

Is it possible to customize a django application to have accept localized date format (e.g dd/mm/yy) in a DateField on an admin form ?

I have a model class :

class MyModel(models.Model):    
    date  = models.DateField("Date")    

And associated admin class

class MyModelAdmin(admin.ModelAdmin):
     pass

On django administration interface, I would like to be able to input a date in following format : dd/mm/yyyy. However, the date field in the admin form expects yyyy-mm-dd.

How can I customize things ? Nota bene : I have already specified my custom language code (fr-FR) in settings.py, but it seems to have no effect on this date input matter.

Thanks in advance for your answer

+2  A: 

The admin system uses a default ModelForm for editing the objects. You'll need to provide a custom form so that you can begin overriding field behaviour.

Inside your modelform, override the field using a DateField, and use the input_formats option.

MY_DATE_FORMATS = ['%d/%m/%Y',]

class MyModelForm(forms.ModelForm):
    date = forms.DateField(input_formats=MY_DATE_FORMATS)
    class Meta:
        model = MyModel

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm
Ben James
It works ! Thanks for your answer ! Tom
tomjerry
Glad it works, maybe you could accept this answer? Welcome to Stack Overflow by the way.
Ben James
of course, sorry ! I'm not used to this website :-)
tomjerry
A: 

The fix proposed by Ben is working but the calendar on the right is not shown anymore.

Here is an improvement. The calendar will still be shown and the date will be displayed with the %d%%M/%Y format.

from django.forms.models import ModelForm
from django.contrib.admin.widgets import AdminDateWidget
from django.forms.fields import DateField  

class MyModelForm(ModelForm):
    date = DateField(input_formats=['%d/%m/%Y',],widget=AdminDateWidget(format='%d/%m/%Y'))
    class Meta:
        model = MyModel

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm

When clicking on a day in the calendar, the value of the field has the %Y-%m-%d format but is is accepted as a valid date format.

PS: Thanks to Daniel Roseman for his answer to this question

luc