Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django DateTimeField save

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

like image 492
Павел Тявин Avatar asked Jan 23 '26 06:01

Павел Тявин


1 Answers

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

like image 124
dm03514 Avatar answered Jan 25 '26 20:01

dm03514



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!