django模型的自动创建日期表单对象? [英] Automatic creation date for django model form objects?
问题描述
自动设置对象的创建日期的最佳方式是什么?还有当上次更新对象时记录的字段?
在我的模型中有:
created_at = models.DateTimeField(False,True,editable = False)
updated_at = models.DateTimeField True,True,editable = False)
在我看来:
if request.method =='POST':
form = MyForm(request.POST)
如果form.is_valid():
obj = form.save(commit = False)
obj.user = request.user
obj.save()
return HttpResponseRedirect('obj_list')
我收到错误:
objects_object.created_at可能不是NULL
我必须手动设置此值吗?我认为这是参数传递给DateTimeFields的点(或者它们只是默认值),并且由于我设置了'editable = False',所以它们不会显示在表单上,因此不会在请求中提交,因此不能填写表格?)。
最好的方法是什么?一个 init 方法?
感谢
ps - 我是一个django和Python新手...
您可以使用 auto_now
和 auto_now_add
updated_at
和 created_at
class MyModel(models.Model):
pre>
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now = True)
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...
解决方案You can use the
auto_now
andauto_now_add
options forupdated_at
andcreated_at
respectively.class MyModel(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
这篇关于django模型的自动创建日期表单对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!