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
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.
Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the 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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With