edu222
edu222

Reputation: 496

Django display charfield field that represents minutes as hh hours, mm minutes

I have a field in Django that is a models.CharField .

It stores the duration of a movie.

For a movie that lasts 90min, when I call it from a template, something like

{{ movie.duration }}

I would like to get 1 hour, 30 minutes instead of 90min.

Upvotes: 1

Views: 2529

Answers (2)

savick01
savick01

Reputation: 101

You should probably just use models.TimeField instead of CharField.

If you really need a way to convert a string number into a string time (in decorator or wherever), you can (over)do it using the time type and one of its powerful methods:

from datetime import time    

def num_to_time(snum):
    num = int(snum)
    ttime = (num / 60, num % 60)
    return time.strftime('%k h %M s')[1:]
    #[1:] just because %k produces one leading space

Upvotes: 0

bwooceli
bwooceli

Reputation: 371

I like the duration_formatted function idea, but I would recommend a template filter vs. model

from django import template

register = template.Library()

@register.filter('duration_format')
def duration_format(value):
    value = int(value)
    h = 'hour'
    m = 'minute'
    hours = int(value/60)
    minutes = value%60
    if hours <> 1:
        h += 's'

    if minutes <> 1:
        m += 's'

    return '%s %s , %s %s' % (hours, h, minutes, m)

Then in your template you can (assuming the filter is in something like my_template_tags.py)

{% load my_template_tags %}

{% block content %}
<p>{{ film.title }} - {{ film.duration|duration_format }}</p>
{% endblock %}

Upvotes: 4

Related Questions