2

In my Django application I have a DateField (format 'YYYY-MM-DD'). When I try to save the string '2011-11-01' I get no error but my fields gets the NULL value.

I tried to do that with strptime function from datetime and time libraries but with the same issue. Basically it all happens in a form

I have

    if form.valid():
        form.cleaned_data['date'] = year + '-' + month + '-' day
        form.save()
    
bogtan
  • 825
  • 2
  • 13
  • 23

2 Answers2

2

part of the form validation inclues cleaning the data. the cleaned_data dict contains python objects, not the (string) post data.

so form.cleaned_data['data'] needs to be a datetime object (or you need to edit the form or post data before cleaning)

second
  • 28,029
  • 7
  • 75
  • 76
0

I think you should check the model object that accepts the date object and confirm that you did not set it to always be null ... Actually I think the misnomer is there, not in the view or save method but in the model object that should take a date object. Maybe you should consider posting your model code here so we see.

Peter
  • 6,509
  • 4
  • 30
  • 34
  • The problem was that I was writing data in form.cleaned_data and it seems that it's not correct. The correct way to do this is to make f = form.save(commit=False) then f.date = datetime(year,month,day) then f.save() form.save_m2m()...Thank you all and hope this is helpful for you too. – bogtan Nov 01 '11 at 13:37
  • I will make some research to see why the way I was doing is not correct – bogtan Nov 01 '11 at 13:37