tags:

views:

46

answers:

1

What's the best way to set a creation date for an object automatically, and also a field that will record when the object was last updated?

In my model I have:

created_at = models.DateTimeField(False, True, editable=False)
updated_at = models.DateTimeField(True, True, editable=False)

and in my view:

if request.method == 'POST':
    form = MyForm(request.POST)
    if form.is_valid():
        obj = form.save(commit=False)
        obj.user = request.user
        obj.save()
        return HttpResponseRedirect('obj_list')

I get the error:

objects_object.created_at may not be NULL

Do I have to manually set this value myself? I thought that was the point of the parameters passed to the DateTimeFields (or are they just defaults, and since I've set 'editable=False' they don't get displayed on the form, hence don't get submitted in the request, and therefore don't get put into the form?).

What's the best way of doing this? An init method?

Thanks

ps - I'm a django and Python newbie...

+2  A: 

You can use the auto_now and auto_now_add options for updated_at and created_at respectively.

class MyModel(models.Model):
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)
Manoj Govindan
Thanks, I thought that's what I was doing. I didn't know I had to name the parameters.
Roger