ModelForm中的DurationField格式 [英] DurationField format in a ModelForm

查看:130
本文介绍了ModelForm中的DurationField格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含持续时间字段的Django模型:

  class Entry(models.Model):
持续时间= models.DurationField()

我想使用ModelForm为该模型渲染一个表单:

  class EditEntryForm(forms.ModelForm):
class Meta:
model = Entry
字段= ['持续时间']

这都是正常的。但是,如果编辑现有模型,则在文本框中呈现的持续时间的格式为 HH:MM:SS



我永远不会处理一个多小时的持续时间。我如何更改Django将表单中的字段格式化为 MM:SS 的方式?



我已经在呈现模型时使用了自定义模板过滤器,我只是想不出如何更改表单的呈现方式。



谢谢

解决方案

您应该可以通过为字段提供自定义小部件来实现此目的:



<$ p从django.forms.widgets导入$ p> 从django.utils.dateparse导入TextInput
导入parse_duration

class DurationInput(TextInput):

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

seconds = duration.seconds

分钟=秒// 60
秒=秒%60

分钟=分钟%60

返回'{:02d}:{:02d}'。format(分钟,秒)

,然后在字段上指定此小部件:

  cla ss EditEntryForm(forms.ModelForm):
类Meta:
模型=条目
字段= ['duration']
小部件= {
'duration':DurationInput( )
}

当然,如果供应时间超过一个小时...


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

解决方案

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

这篇关于ModelForm中的DurationField格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆