Reputation: 907
I have a model like this
class Timer(models.Model):
"""Represents a timing system"""
start_time = models.DateTimeField(default=datetime.datetime.now())
end_time = models.DateTimeField()
and a form that takes this as the model
class JobForm(forms.ModelForm):
class Meta:
exclude = ['slug','author','duration',]
model = Job
Trouble comes in when i want to add some timing info, and by that i mean that i have to enter it in the long format
DD-MM-YYYY HH:MM:SS
the times will be added in real time on the same day as they happen, so the long format looks like a waste of effort, i would rather do it as
HH:MM
i cant use model.TimeField because i will calculate a duration between a start time and the end time, and someone may straddle midnight by timing their sleep or who knows what else. How would i allow input in HH:MM and have it as datetimefield (eventualy after some effort)? Id like the code to assume the same date as the current date give HH:MM
Upvotes: 1
Views: 1466
Reputation: 907
After looking at the forms documentation, this is what iv decided to do, since i didn't understand @cclerville's suggestion (maybe django is poor?) here goes: in my forms.py
class MyDateTimeField(forms.Field):
def to_python(self, value):
# Return an empty list if no input was given.
if not value:
return []
import datetime
today = datetime.date.today()
hhmm = value.split(':')
val= datetime.datetime.combine(datetime.date.today(), datetime.time(int(hhmm[0]),int(hhmm[1])))
return val
and the form itself:
class JobForm(forms.ModelForm):
end_time = MyDateTimeField()
Upvotes: 1