Python/Django convert/humanize specific dictionary items on django view?
<p>I am creating a variable queryset and then passing the values into a dictionary context variable. I am able to convert dates but I'm not sure how to convert specific fields to currency (example: $1,000 instead of 1000) or even just humanize specific fields with commas (1,000 instead of 1000) below is my code from my view, the two methods are a part of a class:</p>

<pre><code>from datetime import date

def get_context_data(self):
    context = super(MyView, self).get_context_data()
    context['myview_items'] = self.get_mymethod_items_context()
    return context

def get_mymethod_items_context(self):
    context = {}
    items = table.objects.values('date_begun', 'price', 'item_number')

    context['items'] = items
    context['headers'] = ['Date', 'Price', 'Item']
    context['fields'] = ['date_begun_date', 'price', 'item_number']
    return context
</code></pre>

<p>I only want to convert one field, which is what I was trying to do for the price field:</p>

<pre><code>from django.contrib.humanize.templatetags.humanize import intcomma 
intcomma('price')
</code></pre>

<p>How im creating tables, Template tag on my template:</p>

<pre><code>{% simple_table_print 'tableid1' 'Price Information' myview_items.items myview_items.fields myview_items.headers %}  
</code></pre>

<p>Usually it's a payment processor headache. But if you want to localize your currency value I'd suggest sth like that:</p>

<p>Use <a href="http://babel.pocoo.org/en/latest/index.html" rel="nofollow">'babel'</a> app as a base &amp; implement the following filter:</p>

<pre><code>from decimal import Decimal
from decimal import InvalidOperation

from babel.numbers import format_currency
from django.utils.translation import get_language, to_locale


@register.filter
def currency_format(value, currency = 'USD'):
    try:
        value = Decimal(value)
    except (TypeError, InvalidOperation):
        return u''        

    kwargs = {
        'currency': currency,
        'locale': to_locale(get_language() or settings.LANGUAGE_CODE)

    return format_currency(value, **kwargs)
</code></pre>

<p>You can use it as a filter or in your views by calling <code>currency_format()</code> directly.</p>

python django dictionary type-conversion