diff --git a/lifting/templatetags/__init__.py b/lifting/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/lifting/templatetags/lifting.py b/lifting/templatetags/lifting.py new file mode 100644 index 0000000..479d22f --- /dev/null +++ b/lifting/templatetags/lifting.py @@ -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) diff --git a/lifting/utils.py b/lifting/utils.py new file mode 100644 index 0000000..4f37083 --- /dev/null +++ b/lifting/utils.py @@ -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 diff --git a/templates/lifting/day.html b/templates/lifting/day.html index 39fe683..0ebf7d7 100644 --- a/templates/lifting/day.html +++ b/templates/lifting/day.html @@ -1,4 +1,6 @@ {% extends "base.html" %} +{% load lifting %} + {% block content %}
@@ -23,7 +25,7 @@ {% for set in sets %} {{set.exercise}} - {{set.weight_kg}} kg + {% mass_unit set.weight_kg %} {{set.reps}} {% endfor %}