djangomodelformmultivaluedjango-multiwidget

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


My Journey model contains two fields, distance and time:

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

I am trying to create a Modelform where the time field will be split to display inputs for 'hrs', 'min' and 'sec'. I would then like these values to be compressed in order to return one single value. Currently my forms.py looks like this:

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"]

I am receiving TypeError: __init__() got an unexpected keyword argument 'attrs' when I attempt to run the server. Is anyone able to help me understand how to fix this? I have been searching for a solution online for some time but so far am still stumped.


Solution

  • You can try to create DurationField instead:

    class Journey(models.Model):
        distance = models.PositiveIntegerField(default=0)
        time = models.DurationField()
    
    class DistanceTimeModelForm(forms.ModelForm):
        class Meta:
            model = Journey
            fields = ["distance", "time"]