Gaurav Tomer
Gaurav Tomer

Reputation: 741

How to enforce user to enter a datefield in DD-MM-YYYY format, and timefield in 'HH:MM' format in django?

my models.py:

class Attendancename(models.Model):
    teacher_name = models.ForeignKey(Teachername)
    date = models.DateField('Date')
    intime = models.TimeField('IN-TIME')
    outtime = models.TimeField('OUT-TIME')

my forms.py:

class AttendancenameForm(ModelForm):
    teacher_name = forms.ModelChoiceType(queryset=Teachername.objects.all())
    date = /*** What should I write to enforce 'DD-MM-YYY'?***/
    intime = /*** to enforce 'HH:MM' format?***/

Please provide me suggestions to make it in above format otherwise, It has to raise error against entered input. How can I implement it in django forms?

I also want to calculate total hours based on intime and outtime, how can I implement it in my views.py file?

Upvotes: 1

Views: 327

Answers (1)

Bernhard
Bernhard

Reputation: 8831

django.froms.DateField and django.forms.TimeField both have an input parameter named input_formats which is a list of date and time input formats, respectively. They define what patterns should be attempted when parsing the user input.

date = DateField(input_formats=['%d-%m-%Y'])
intime = TimeField(input_formats=['%H:%M'])

See https://docs.djangoproject.com/en/1.8/ref/forms/fields/# for details.

Upvotes: 2

Related Questions