0

I have few questions regarding the Date and time fields both in the model and in the form class.

1.)In the docs for the date field what does the line "Normalizes to: A Python datetime.date object." mean? Does it mean that the field data stored in the request.POST dictionary on the submission of the form is a datetime.date object?If yes, then when does it do it when the form is submitted or do we have to call one of its functions?

2.)If i have a models.DateField() then while assigning data to it manually in a view should i assign a datetime.date object or a unicode object with the 'yyyy-mm-dd' format?

3.)If i take a date in my forms.DateField() in the '%d/%m/%y' format how do i assign it to my models.DateField() because that seems to accept only the 'YYYY-mm-dd' format?

If somebody could also suggest some links which explain these fields in detail with examples apart from the docs it would be helpful.

BenMorel
  • 34,448
  • 50
  • 182
  • 322

1 Answers1

1

For first question, datefield saves date object and if you are saving any data( for example a string: "01-01-2015") to datefield, then you have to convert that data into date object. You will not get a date object in request.POST, if you use a form, then you can get it by using cleaned_data.(example below) From request.POST ,you will get an unicode object.( then you will need to convert it to date object, example below)

For second question, obviously you have to save dateobject, not unicode object.

For third question, in forms, To display initial field value properly formatted, use DateInput widget. To customize validation, use input_formats keyword argument of DateField. Here, from forms, you will get a date object in views, so it can be saved directly, like:

In model.py:

class DateModelClass(models.Model):
    date= models.DateField()

In forms.py:

date= forms.DateField(widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=('%d/%m/%Y',))

In views.py:

date_data= DateModelClass(date= form.cleaned_data['date'])
date_data.save()

Also you can convert a string of your desired format to Date Object like this:

>>import datetime
>>datetime.datetime.strptime(u"09/07/2014", '%d/%m/%Y').date()
Community
  • 1
  • 1
ruddra
  • 50,746
  • 7
  • 78
  • 101