Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DurationField format in a ModelForm

I have a Django model that contains a duration field:

class Entry(models.Model):
    duration = models.DurationField()

And I want to render a form for this model using a ModelForm:

class EditEntryForm(forms.ModelForm):
    class Meta:
        model = Entry
        fields = ['duration']

Which is all working. However, if editing an existing model, the duration rendered in the text box is of the format HH:MM:SS

I will never be dealing with durations over an hour. How can I change how Django is formatting this field in the form to just be MM:SS?

I already have a custom template filter in use when rendering the model, I just can't figure out how to change how the form is rendered.

Thanks

like image 917
MichaelM Avatar asked Oct 12 '15 10:10

MichaelM


People also ask

What is DurationField in Django?

DurationField is a field for storing periods of time – modeled in Python by timedelta. When used on PostgreSQL, the data type used is an interval and on Oracle the data type is INTERVAL DAY(9) TO SECOND(6). Otherwise, a bigint of microseconds is used.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

How do you create a model form?

First, create a model that contains fields name and other metadata. It can be used to create a table in database and dynamic HTML form. This file contains a class that inherits ModelForm and mention the model name for which HTML form is created. Write a view function to load the ModelForm from forms.py.

What is model form?

Model Forms are forms that are connected directly to models, allowing them to populate the form with data. It allows you to create a form from a pre-existing model. You add an inline class called Meta, which provides information connecting the model to the form. An inline class is a class within another class.


1 Answers

You should be able to do this by providing a custom widget for the field:

from django.forms.widgets import TextInput
from django.utils.dateparse import parse_duration

class DurationInput(TextInput):

    def _format_value(self, value):
        duration = parse_duration(value)

        seconds = duration.seconds

        minutes = seconds // 60
        seconds = seconds % 60

        minutes = minutes % 60

        return '{:02d}:{:02d}'.format(minutes, seconds)

and then you specify this widget on the field:

class EditEntryForm(forms.ModelForm):
    class Meta:
        model = Entry
        fields = ['duration']
        widgets = {
            'duration': DurationInput()
        }

Of course, this will cause weirdness if you do ever supply durations longer than an hour...

like image 53
solarissmoke Avatar answered Dec 14 '22 10:12

solarissmoke