DurationField format in a ModelForm

后端 未结 2 1463
感动是毒
感动是毒 2021-01-05 15:44

I have a Django model that contains a duration field:

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

And I want to render

2条回答
  •  离开以前
    2021-01-05 16:28

    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...

提交回复
热议问题