0

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.

Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
sgt_pepper85
  • 421
  • 4
  • 14

1 Answers1

1

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"]
Andrey Borzenko
  • 718
  • 5
  • 8
  • Thank you, that certainly improves my output, although it still only allows the user to input their time in seconds. I would like them to have three input boxes within one field for 'hrs', 'min', and 'sec' – sgt_pepper85 Oct 09 '20 at 06:32
  • 1
    You can use this duration widget https://pypi.org/project/django-durationwidget/ – Andrey Borzenko Oct 09 '20 at 06:55