add weight conversion tag and use it

This commit is contained in:
James Turk 2015-04-06 14:53:17 -04:00
parent d893aabf91
commit cd02ca4684
4 changed files with 43 additions and 1 deletions

View File

View File

@ -0,0 +1,29 @@
import decimal
from django import template
from django.template.defaultfilters import stringfilter
from lifting.utils import round_to
register = template.Library()
class MassNode(template.Node):
def __init__(self, weight):
self.weight = template.Variable(weight)
def render(self, context):
try:
weight_kg = self.weight.resolve(context)
return round_to(weight_kg * decimal.Decimal("2.2046"), decimal.Decimal("0.125"))
except template.VariableDoesNotExist:
return ''
@register.tag
def mass_unit(parser, token):
try:
tag_name, weight = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError(
"{!r} tag requires exactly one argument".format(tag_name)
)
return MassNode(weight)

11
lifting/utils.py Normal file
View File

@ -0,0 +1,11 @@
import decimal
def round_to(number, increment, up_threshold=0.95):
""" round number to nearest multiple of increment """
ratio = number/increment
whole = ratio.to_integral(rounding=decimal.ROUND_DOWN)
dec = ratio - whole
if dec >= up_threshold:
whole += 1
return whole * increment

View File

@ -1,4 +1,6 @@
{% extends "base.html" %}
{% load lifting %}
{% block content %}
<section class="row header-row">
@ -23,7 +25,7 @@
{% for set in sets %}
<tr>
<td>{{set.exercise}}</td>
<td>{{set.weight_kg}} kg</td>
<td>{% mass_unit set.weight_kg %}</td>
<td>{{set.reps}}</td>
</tr>
{% endfor %}