0

My Journey 模型包含两个字段,距离和时间:

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

我正在尝试创建一个 Modelform,其中时间字段将被拆分以显示“小时”、“分钟”和“秒”的输入。然后,我希望压缩这些值以返回一个值。目前我的 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'尝试运行服务器时收到。有谁可以帮助我了解如何解决这个问题?我一直在网上寻找解决方案一段时间,但到目前为止我仍然很难过。

4

1 回答 1

1

您可以尝试创建 DurationField 代替:

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

class DistanceTimeModelForm(forms.ModelForm):
    class Meta:
        model = Journey
        fields = ["distance", "time"]
于 2020-10-09T06:03:56.423 回答