[Solved]Django Duration Field usage.

Solved see bottom

I am trying to work with a durationfield.
The goal is that the client inputs a duration in the format of HH:MM (I wrote a small js snippet that enforces this format in the form) and this duration should then be usable a a python duration to do operations with(such as adding durations for statistic purposes). Yet I am unable to get it to work as it keeps throwing the error unsupported type for timedelta microseconds component: str

Simplified version of my code:


class Foo(models.Model):
    bar = models.Charfield(max_length=255)
    duration = models.DurationField()


class FooForm(ModelForm):
    class Meta:
      model = Foo
      fields = '__all__'
      labels = {}
      widgets = {
      'duration' = TextInput(attrs={'class':'durationInputWidget'})


def fooAdd(request):
  if request.method == 'POST':
    newRequest = request.POST.copy()
        dur = request.POST.get('duration')
        dur = dur.split(':')
        dur = f"PT{dur[0]}H{dur[1]}M"
        dur = "PT0M"
        'dur': dateparse.parseduration(dur) #it does not seem to matter whether I call parseduration here

    form = FooForm(newRequest)#Breakpoint here
    if form.is_valid():
      return redirect("index")
     form = FooForm()
  return render(request, 'template.html', {'form': form})

Using a debugger to look at the breakpoint yields the following result for the duration variable(using an input into the form of 02:00):
['02:00', datetime.timedelta(seconds=7200)]
I have no clue why this is a list and where the first entry comes from other than that django.utils.dateparse.duration returns it as such(the documentation however says it should only return the timedelta object).

This error seems to occur after form.save and when rendering something else that uses the foo model(this something else does not use the duration, which is why I added bar to models.py in the database (sqlite) the timedelta seems to be correctly saved as milliseconds; django itself says the error is happening in my base.hmtl at the following line:
<link rel="shortcut icon" type="image/x-icon" href="{% static 'images/fav.ico' %}">
This however does nothing but add a icon which should never throw a
TypeError - unsupported type for timedelta microseconds component: str. Of note however is that the when manually examining the table it is saving the value as chars. I will try to completely recreate the database.

Dropping and recreating the database fixed my current issue, it seems to have been leftover from when foo was a duration field however I have now run into the new issue that when editing foo objects via a form the duration fields dont get populated with the saved timedeltas. As this is an issue with my javascript I consider this issue now fixed(by default it gets displayed as HH:MM:SS)

1 Like