DurationField format in a ModelForm

后端 未结 2 1461
感动是毒
感动是毒 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:16

    In my case i needed to remove the milliseconds so i did what MichaelM suggested by

    # -*- coding: utf-8 -*-
    
    import datetime
    
    from django import forms
    
    from harvests.models import Harvest
    
    
    def duration_string(duration):
        # Removing the milliseconds of the duration field
        days = duration.days
        seconds = duration.seconds
        microseconds = duration.microseconds
    
        minutes = seconds // 60
        seconds = seconds % 60
    
        hours = minutes // 60
        minutes = minutes % 60
    
        string = '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
        if days:
            string = '{} '.format(days) + string
        # if microseconds:
        #     string += '.{:06d}'.format(microseconds)
    
        return string
    
    
    class CustomDurationField(forms.DurationField):
        def prepare_value(self, value):
            if isinstance(value, datetime.timedelta):
                return duration_string(value)
            return value
    
    
    class HarvestForm(forms.ModelForm):
        work_time_interval = CustomDurationField()
    
        class Meta:
            model = Harvest
            fields = '__all__'
    

提交回复
热议问题