← Back to list

Make your own String Format in Python/Django

Python f-strings are often enough for all your string formatting needs, but sometimes in Django especially in HTML templates, formatting a…

Dennis CM · 2026-04-23 13:14 · 5 claps · 2.5 min read
#python #django #python-string-format #dennis-meneses
Open on Medium ↗
Wiki topics: GEN · Genomics & Sequencing 🌐 · Web Development

Make your own String Format in Python/Django

Python **f-strings are often enough for all your string formatting needs, but sometimes in Django **especially in HTML templates, formatting a (data) model object is a bit of a challenge.

The good thing is, you can make it easy by implementing Python’s format method in your model class :)

Note that codes included here are partial source codes, only the specific code blocks that are relevant are posted here, and it assumes you are familiar with Django.

Model

The main focus here is the format method of our class, which supports 2 custom formats (combo & details) and depending on which one is passed, we return a different value:

class Product(models.Model):
    item_name = models.CharField(max_length=24)
    item_price = models.FloatField(default=0.0)
    item_description = models.CharField(max_length=255)

    def __format__(self, format_spec):
        fs = str(format_spec).strip().lower()
        if fs == 'combo':
            return f"{self.item_name} at $ {self.item_price}"
        elif fs == 'details':
            return self.item_description
        else:
            return self.item_name

views.py | API endpoint

Our first use of format would be for an API endpoint and for simplicity, we’ll just return a list of the formatted value inside a dictionary:

from django import http
from . import models

def api(request: http.HttpRequest) -> http.HttpResponse:
    # for demo only; in real-world, you filter the dataset
    products = models.Product.objects.all()

    results = []
    for product in products:
        entry = {
            'listing': f"{product:combo}",
            'description': f"{product:details}"
        }
        results.append(entry)

    return http.JsonResponse(results, safe=False)

Here’s a sample of what that would look like:

views.py | HTML (page) endpoint

The other use case is for use in (html) templates, which makes formatting objects a bit challenging.

To use our format in Django templates, we’ll need to do an extra step.

In the meantime, here’s the code for this endpoint:

def index(request: http.HttpRequest) -> http.HttpResponse:
    # for demo only; in real-world, you filter the dataset
    products = models.Product.objects.all()

    return render(request, 'demo/content.html', context={'products': products})

Setting up the Django template tags

Go to your apps folder (not the project, the apps folder) and create a “templatetags” folder with an empty “init.py” in it.

From there, create a new script that we’ll register — call it “product_tags.py”. If your project name is “demo”, your project tree should look like this:

demo
  +---- templatetags
          +----------- __init__.py
          +----------- product_tags.py

template tags | product_tags

Now copy the code below to register a new formatter; we’ll just name it “fmt” for simplicity:

from django import template

register = template.Library()

@register.filter(name='fmt')
def _(value, format_spec):
    try:
        return format(value, format_spec)
    except (ValueError, TypeError):
        return value

templates | HTML

Now in our HTML file, we can use this “fmt” that we registered to use our custom class format spec:

<h2>Product List</h2>

    <ul>
        {% for product in products %}
            <li>
                <p>
                    {{ product|fmt:"combo" }}<br/>
                    {{ product|fmt:"details"}}
                </p>

            </li>
        {% endfor %}
    </ul>

Here’s what that would look like:

It’s unlikely that you’ll use format in most of your day-to-day job or projects, but should you need to, you’ll know how to :)

As the saying goes … “better to have it and not need it, that to need it and not have it” :)


메타데이터
post_id
39642c21091f
slug
make-your-own-string-format-in-python-django-39642c21091f
url
https://medium.com/@pjonsms/make-your-own-string-format-in-python-django-39642c21091f
canonical_url
https://medium.com/@pjonsms/make-your-own-string-format-in-python-django-39642c21091f
author_url
https://medium.com/@pjonsms
status
ok
fetched_at
2026-06-24 04:09:36