如何拆分表单字段以在 Django 中显示多个值

How to split a form field to display multiple values in Django

我的旅程模型包含两个字段,距离和时间:

class Journey(models.Model):
    distance = models.PositiveIntegerField(default=0)
    time = models.PositiveIntegerField(default=0)

我正在尝试创建一个模型表单,其中时间字段将被拆分以显示 'hrs'、'min' 和 'sec' 的输入。然后我想压缩这些值以便 return 一个值。目前我的 forms.py 看起来像这样:

from django import forms
from django.forms import MultiWidget
from .models import Journey


class DistanceTimeModelForm(forms.ModelForm):
    time = forms.MultiValueField(
        widget=MultiWidget(
            widgets=[
                forms.IntegerField(attrs={"placeholder": "hrs"}),
                forms.IntegerField(attrs={"placeholder": "min"}),
                forms.IntegerField(attrs={"placeholder": "sec"}),
            ]
        ),
        require_all_fields=True,
        error_messages={"incomplete": "Please enter a number"},
    )

    class Meta:
        model = Journey
        fields = ["distance", "time"]

当我尝试 运行 服务器时收到 TypeError: __init__() got an unexpected keyword argument 'attrs'。有谁能帮助我了解如何解决这个问题?我一直在网上寻找解决方案有一段时间了,但到目前为止仍然很困惑。

您可以尝试创建 DurationField:

class Journey(models.Model):
    distance = models.PositiveIntegerField(default=0)
    time = models.DurationField()

class DistanceTimeModelForm(forms.ModelForm):
    class Meta:
        model = Journey
        fields = ["distance", "time"]