stop overprocessing views

Date: March 31st 2016
Last updated: March 31st 2016

This entry follows on from custom template filters. I have realised that I am overprocessing in This example shows how to pass an object to a template and provide some filtering using custom templatetags.

The objective of the following code is to convert a decimal field into a fraction which is rendered in HTML. Previously I had been evaluating/processing data in and then sending a new dictionary to the HTML template. Here I use a custom template filter to do the work.

def profilepage(request, surfer_id):
    surfer = get_object_or_404(Surfer, pk=surfer_id)
    #<- snipped ->
    boardstest = (surfer.boards.all()) #<===== query all boards for this surfer
    return render(request, 'surferprofile/profile.html',
                    {'boardstest': boardstest})

from django import template
import math
from fractions import Fraction

register = template.Library()

def fractioncreator(value):
    Convert a decimal field into a fraction
    >>> 2 3/8
    return '{} {}'.format(str(math.floor(value)), str(Fraction(value % 1)))

def width_as_fraction(value):
    return fractioncreator(value)

profile.html (minimal)

    {% for board in boardstest %}
        <!-- use the templatetag to filter the decimal field: boardwidth -->
    {% endfor %}

profile.html (Used with other fields)

    {% for board in boardstest %}
        <!-- get str function -->
        <!-- use the templatetag to filter the decimal field: boardwidth -->
        (w/ {{board.boardwidth|width_as_fraction}}
        <!-- capture display label for boardtail for each object -->

        {% if == %}
        {% else %}
        {% endif %}
    {% endfor %}
</div> (profile page)

results matching ""

    No results matching ""