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

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

问题描述

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

I have a Django model that contains a duration field:

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

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

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

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

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

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

我永远不会处理超过一个小时的持续时间.如何将 Django 在表单中格式化此字段的方式更改为 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.

谢谢

推荐答案

您应该能够通过为该字段提供自定义小部件来做到这一点:

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天全站免登陆