Questions & Answers

How to render differently a django model object field on a html page?

My model object have a IntegerField but I want to be able to render it differently on my html page, like lets say the object IntegerField is 500000 I want to render it as 500 000$ on my html page. So Add a space before the last 3 number and add a $ at the end.

I have a models with a IntegerField that look like this

class Listing(models.Model):
    listing_price = models.IntegerField(max_length=100)

In my view I extract the models like this

def home(request):
    listing_object = Listing.objects.all()
    context = {
        "listing_object": listing_object,
    return render(request, "main/index.html", context)

I render the data like this

{% for listing in listing_new_object %}
{% endfor %}
Answers(1) :

You have two options:

  • Manipulate the context to make a list of tuples:
context = {
    "listing_object": [(listing, f'{listing.listing_price:,}'.replace(",", " ")) for listing in listing_object]

then in your template:

{% for _, price in listing_new_object %}
{% endfor %}
  • The other option is to make a Django template filter
{{ listing.listing_price|price_format }}
from django import template

register = template.Library()

def price_format(value):
    return f'{value:,}'.replace(",", " ")