I have modeled a class called ConversationHistory. Whenever an instance is created I wish to set the current date and current time.
class ConversationHistory(models.Model): contact_date = models.DateField(_(u"Conversation Date"), blank=True) contact_time = models.DateTimeField(_(u"Conversation Time"), blank=True) def __init__(self, *args, **kwargs): super(ConversationHistory, self).__init__(*args, **kwargs) self.contact_date = datetime.datetime.now() self.contact_time = datetime.datetime.now()
The idea is that the user can later still adjust the date and time as two different fields.
I am now a bit lost how to make the time field only to show and accept time, rather than date and time. I recon it is not possible to have a time field without datetime, but then how would I show only the time in the form?
If you want only time, TimeField is what you need:
class ConversationHistory(models.Model): contact_date = models.DateField(_(u"Conversation Date"), blank=True) contact_time = models.TimeField(_(u"Conversation Time"), blank=True)
You can take advantage of the auto_now_add
option:
class TimeField([auto_now=False, auto_now_add=False, **options])
A time, represented in Python by a datetime.time instance. Accepts the same auto-population options as DateField.
If you use the auto_now_add
, it will automatically set the field to now when the object is first created.
class ConversationHistory(models.Model): contact_date = models.DateField(_(u"Conversation Date"), auto_now_add=True, blank=True) contact_time = models.TimeField(_(u"Conversation Time"), auto_now_add=True, blank=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With