Currency Inputs Using Bootstrap and Django Crispy Forms

A frequent requirement is to include a ‘$’ on currency inputs. Bootstrap has functionality to do this, but it is not easy to find in the docs. Here is an example:

Screenshot from 2015-03-09 10:12:04

Which is accomplished using:

<form class="form-inline">
  <div class="form-group">
    <label class="sr-only" for="exampleInputAmount">Amount (in dollars)</label>
    <div class="input-group">
      <div class="input-group-addon">$</div>
      <input type="text" class="form-control" id="exampleInputAmount" placeholder="Amount">
      <div class="input-group-addon">.00</div>
    </div>
  </div>
  <button type="submit" class="btn btn-primary">Transfer cash</button>
</form>

Cool… except how to get that markup using crispy? Turns out the creators of crispy have already figure it out. Here is an example:

from crispy_forms.layout import Layout
from crispy_forms.bootstrap import PrependedText

Layout('a field', 'another field', PrependedText('currency field', '$'))

Keepin’ it crispy!

Django Template Filter for Formating Currency

This is a consolidation of stuff on Stackoverflow. It works with Django 1.7.

The goal, format floats, with 2 decimal places and commas every three digits to the left of the decimal:

  1. Add {% load humanize %} to the top of the template
  2. {{ my_float_var|floatformat:”2″|intcomma }}

On Stackoverflow, some posts tell you to add humanize to your installed apps in settings. I suspect that sometime in the past, humanize was not part of the Django standard library. I am using Django 1.7 and it was not necessary.

Add $ Prefix

If you want to add a prefix such as $ when there is an amount, but not when the field is blank, then a custom template is the way to go. First, read the Django docs for the basics of creating custom template tags. Then make this tag:

from django import template
from django.contrib.humanize.templatetags.humanize import intcomma

register = template.Library()

@register.filter
def prepend_dollars(dollars):
    if dollars:
        dollars = round(float(dollars), 2)
        return "$%s%s" % (intcomma(int(dollars)), ("%0.2f" % dollars)[-3:])
    else:
        return ''

Now in your template, put:

{{ my_float_var | prepend_dollars }}