views:

223

answers:

3

I have a slight issue with dates in Django and Google App Engine:

I have the following class because I want date input in the form of DD/MM/YY:

class MyForm(ModelForm): 
      mydate = forms.DateTimeField(input_formats=['%d-%m-%y', '%d/%m/%y']) 
      class Meta: 
          model = MyObject

This works for entering into the datastore. However when I use a generic view to edit the data the form comes back in the format of YYYY-MM-DD. Any ideas on how to change that?

+1  A: 

A DateTimeField will return a datetime.datetime as its value, so you can use any of the usual methods defined in that module for formatting the data. In Django templates, you can use the date, or time filters:

{{my_obj.mydate|date:"D d M Y"}}

Which prints something like:

Wed 09 Jan 2008

(See http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date for details)

dcrosta
I know that but I am talking about the format in an Edit box when using a generic view. I get it back in the format of YYYY-MM-DD in the form
Peter Newman
Ah, it seems I misread your question.
dcrosta
+2  A: 

forms.DateInput takes a format keyword argument, and this can be used to control the format that is represented (I seem to remember, anyway):

class MyForm(ModelForm): 
      mydate = forms.DateField(widget=forms.DateInput(format="%d/%m/%y")) 
      class Meta: 
          model = MyObject

I ended up subclassing both the Field and the Widget, as I wanted to be able to control the formats even more.

Matthew Schinckel
A: 

I used

def date_format(self, instance, **kwargs):
 return getattr(instance,self.name) and getattr(instance,self.name).strftime('%d %m %Y')

from google.appengine.ext.db.djangoforms import DateProperty 
 DateProperty.get_value_for_form = date_format
msmart