Reputation: 2649
I have a model
class Unit(models.Model):
date = models.DateTimeField()
name = models.CharField(max_length = 128)
Then I have a view with js jquery ui datepicker. Then I have an ajax post function with
data_send['date'] = $('#date').value;
data_send['name'] = $('#name').value;
$.post("/url_1/",data_send, function(data_recieve){
alert(data_recieve);
});
Then in a view I'm trying to save unit like
def url_1(request):
unit = Unit.objects.get(pk = 1)
unit.date = request.POST['date']
unit.name = request.POST['name']
unit.save()
return HttpResponse('ok')
Unit.name changes, but not unit.date. I use django 1.3. I have no csrf protection. I recieve 'ok' from server. Why does the unit.date not save?
Thanks
Upvotes: 2
Views: 18050
Reputation: 55932
Since django datetime field is a representation of a datetime.datetime
python instance, I like to make sure that I have a valid instance before inserting into the database.
you can use the datetime module to achieve this, instead of saving unit.date
as a string
from datetime import datetime
try:
valid_datetime = datetime.strptime(request.POST['date'], '%d-%m-%Y')
except ValueError:
# handle this
then you can save the valid_datetime as your unit.date
the second param of strptime is formatted using the below values, it should match your datepicker format http://docs.python.org/library/datetime.html#strftime-strptime-behavior
Upvotes: 9