1

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

mike
  • 897
  • 2
  • 10
  • 29
  • You are probably looking for something like this :http://stackoverflow.com/questions/9954498/django-datefield-and-timefield-to-python-datetime – cclerv Feb 14 '13 at 21:00
  • Drop the parenthesis in `default=datetime.datetime.now()` and also try to change `format` option of the [DateTimeInput widget](https://docs.djangoproject.com/en/dev/ref/forms/widgets/#datetimeinput) else [make your own widget](https://docs.djangoproject.com/en/dev/ref/forms/widgets/). Sorry but I don't have more time ... – jpic Feb 14 '13 at 21:01
  • 1
    Example HH:MM:SS widget and field - http://stackoverflow.com/questions/13824266/django-custom-widget-to-split-an-integerfield-into-hours-and-seconds-fields-in-a/13825412#13825412 – Aidan Ewen Feb 14 '13 at 22:09

1 Answers1

1

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()
mike
  • 897
  • 2
  • 10
  • 29