django forms DateField

Nikhil Verma picture Nikhil Verma · Mar 29, 2011 · Viewed 10.2k times · Source

I have a field in my my form named birthdate like:

class Personal_info_updateForm(forms.Form):
   birthdate = forms.DateField(widget=SelectDateWidget(years=[y for y in range(1930,2050)]))
   ..
   ..

views.py

def personal_info(request):
    mc = MenuCategories()      
    listCategories = mc.getCategories()
    oe = OEConnector()
    if request.method == 'POST':
        f1 = Personal_info_updateForm(request.POST)
        print request.POST
        if f1.is_valid():
            first_name = f1.cleaned_data['first_name']
            last_name = f1.cleaned_data['last_name']
            c=[last_name,first_name]
            name = " ".join(c)
            print name
            birthdate = f1.cleaned_data['birthdate']
            birthdate_year,birthdate_month,birthdate_day=['','','']

            birthdate = [birthdate_year,birthdate_month,birthdate_day]
            c=" ".join(birthdate)
            print birthdate
            title = f1.cleaned_data['title']
            print title
            email = f1.cleaned_data['email']
            mobile = f1.cleaned_data['mobile']
            phone = f1.cleaned_data['phone']
            result = update_details(name,first_name,last_name,birthdate,email,mobile,phone)
            print result
            return HttpResponse('/Info?info="Congratulations, you have successfully updated the information with aLOTof"')

a1.html I am calling the whole form like

<form action="" method="POST">
    <table style="color:black;text-align:left; margin-left: 20px;">
        {{ form.as_table }}
    </table>
    <input type="submit" value="UPDATE">
</form> 

I want that to store the value of my birthdate in Postgresql. But its not working so I have studied that I need to convert it into DateTime Field because date field object is completely different.. Please tell me how do I convert so that I can get rid of this problem. I am taking it as a string..

Thanks in advance

Answer

gladysbixly picture gladysbixly · Mar 29, 2011

As per django docs, http://docs.djangoproject.com/en/dev/ref/forms/fields/#datefield, the value of the date field normalizes to a Python datetime.date object.

So if you have something like birthdate = models.DateField() in your model, assigning the value from the form should be straight forward.

#views.py
birthdate = f1.cleaned_data['birthdate']
my_model_instance.birthdate = birthdate

However, if you still want to convert it into DateTime, assuming you changed your model field into DateTime already, you can either:

  • change the birthdate field of your form from DateField into DateTimeField
  • create a Python datetime.datetime object from the form value

For the second option, you will need to create a datetime.datetime object with the following format:

import datetime
bday = datetime.datetime(year, month, day)

Check out the python docs on datetime and [time][2] for more info.