每次编辑对象时,DateField都会清除自己

时间:2021-05-17 19:21:14

I have the following model:

我有以下模型:

class Day(models.Model):
day = models.DateField()
title = models.CharField(max_length=20)
description = models.CharField(max_length=160)
votes = models.IntegerField(max_length=7)
last_vote = models.DateTimeField()

def __unicode__(self):
    return self.title

Whenever I edit it like this:

每当我这样编辑它:

current_time = datetime.datetime.now()
day_to_vote_for.votes += 1
day_to_vote_for.last_vote = current_time
day_to_vote_for.save()

or whenever I edit through the admin control panel, it is reset to a blank field? Why? This doesn't happen with the Datetime field. How do I fix it?

或者当我通过管理控制面板进行编辑时,它被重置为一个空白字段?为什么?这不会发生在Datetime字段中。我怎么修复它?

People need to be able to specify dates other than now. So auto_now_add won't work. It's just clearing for no reason.

人们需要能够指定日期,而不是现在。所以auto_now_add不会工作。它只是无缘无故地在清理。

1 个解决方案

#1


1  

Just pass auto_now=True if you want the field to be updated with current timestamp whenever you save it or use auto_now_add=True to save the timestamp when the object was actually created.

如果您希望在保存时使用当前时间戳更新字段,或者使用auto_now_add=True保存对象实际创建时的时间戳,那么只需传递auto_now=True。

#1


1  

Just pass auto_now=True if you want the field to be updated with current timestamp whenever you save it or use auto_now_add=True to save the timestamp when the object was actually created.

如果您希望在保存时使用当前时间戳更新字段,或者使用auto_now_add=True保存对象实际创建时的时间戳,那么只需传递auto_now=True。