Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Model a TimeField in Django?

Tags:

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?

like image 765
Houman Avatar asked Jul 08 '12 18:07

Houman


1 Answers

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) 
like image 121
César Avatar answered Oct 21 '22 03:10

César