Django DateField default options

后端 未结 6 1137
醉酒成梦
醉酒成梦 2020-11-30 22:50

I have a model which has a date time field:

date = models.DateField(_(\"Date\"), default=datetime.now())
6条回答
  •  时光取名叫无心
    2020-11-30 23:22

    I think a better way to solve this would be to use the datetime callable:

    from datetime import datetime
    
    date = models.DateField(default=datetime.now)
    

    Note that no parenthesis were used. If you used parenthesis you would invoke the now() function just once (when the model is created). Instead, you pass the callable as an argument, thus being invoked everytime an instance of the model is created.

    Credit to Django Musings. I've used it and works fine.

提交回复
热议问题