Post

The Hidden Django Functions

The Hidden Django Functions

Introduction

Every Django project eventually grows a utils.py file full of small helpers: generate a slug, create a random code, build a link, escape some HTML.

Many of these helpers already exist inside Django. They are tested, secure, and maintained. They are just not where most people look.

This post walks through a set of Django functions that save you from reinventing the wheel, what each one does, and the gotchas that come with it.


Where These Functions Live

Django ships a lot of helpers outside the usual models, views, and forms:

  • django.utils.*: text, crypto, HTML, and functional helpers.
  • django.shortcuts: view shortcuts that wrap common patterns.
  • django.template.loader: template rendering outside of views.
  • django.core.signing: tamper-proof data without a database.

None of them need extra packages. If you have Django installed, you already have them.


1. slugify(): Clean URLs from Any Text

1
2
3
4
from django.utils.text import slugify

slugify("  Hello, World!  ")     # 'hello-world'
slugify("Café Déjà Vu")          # 'cafe-deja-vu'

slugify() converts text to lowercase, removes characters that are not letters, numbers, underscores, hyphens, or spaces, then replaces spaces with hyphens.

Practical usage

1
2
3
4
5
6
7
8
class Article(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super().save(*args, **kwargs)

Gotcha: non-Latin text

By default, slugify() converts text to ASCII. Characters that can’t be converted are dropped. For Arabic (or any non-Latin script), the result can be an empty string:

1
2
slugify("مرحبا بالعالم")                      # ''
slugify("مرحبا بالعالم", allow_unicode=True)  # 'مرحبا-بالعالم'

An empty slug combined with unique=True fails on the second save. If your users write in non-Latin languages, use allow_unicode=True (and SlugField(allow_unicode=True)), or fall back to another value when the slug is empty.

Also note that slugs are not automatically unique. Two articles titled “Hello World” produce the same slug, so you still need to handle collisions.

Ref: django.utils.text.slugify


2. get_random_string(): Secure Random Codes

1
2
3
4
5
6
7
from django.utils.crypto import get_random_string

get_random_string(12)
# e.g. 'aZ3kP9qLm2Xw'

get_random_string(6, allowed_chars="0123456789")
# e.g. '483920'

It uses Python’s secrets module under the hood, so the output is cryptographically secure. That makes it suitable for:

  • Invitation codes
  • One-time verification codes
  • Unique suffixes for slugs or filenames
1
2
3
4
5
6
7
# Common: predictable, not meant for security
import random
code = "".join(random.choice("0123456789") for _ in range(6))

# Recommended: cryptographically secure
from django.utils.crypto import get_random_string
code = get_random_string(6, allowed_chars="0123456789")

The random module is designed for simulations, not security. Its output can be predicted if an attacker observes enough values.

Ref: django.utils.crypto.get_random_string


3. render_to_string(): Templates Outside of Views

A template is not only for full page responses. render_to_string() renders a template to a plain string you can use anywhere.

Note that it lives in django.template.loader, not in django.shortcuts:

1
from django.template.loader import render_to_string

Practical usage: HTML emails

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from django.core.mail import send_mail
from django.template.loader import render_to_string


def send_welcome_email(user):
    context = {"user": user}

    send_mail(
        subject="Welcome!",
        message=render_to_string("emails/welcome.txt", context),
        html_message=render_to_string("emails/welcome.html", context),
        from_email=None,
        recipient_list=[user.email],
    )

Practical usage: HTML fragments for HTMX/AJAX

1
2
3
4
5
6
7
8
9
10
11
12
from django.http import JsonResponse


def add_to_cart(request, product_id):
    cart = add_product(request, product_id)

    html = render_to_string(
        "cart/_summary.html",
        {"cart": cart},
        request=request,
    )
    return JsonResponse({"html": html})

Pass request=request when the template needs context processors (like user, csrf_token, or messages). Without it, those variables are not available.

Ref: render_to_string()


4. redirect(): One Function, Three Inputs

Many developers only use redirect() with a hardcoded URL. It actually accepts three kinds of input:

1
2
3
4
5
6
7
8
9
10
from django.shortcuts import redirect

# 1. A model instance: calls get_absolute_url()
return redirect(article)

# 2. A URL pattern name, with args or kwargs: calls reverse()
return redirect("article-detail", slug=article.slug)

# 3. A relative or absolute URL
return redirect("/articles/")

The first form keeps URL logic inside the model:

1
2
3
class Article(models.Model):
    def get_absolute_url(self):
        return reverse("article-detail", kwargs={"slug": self.slug})

Now every view can just redirect(article), and changing the URL structure means updating one method.

By default, redirect() returns a temporary redirect (302). Pass permanent=True for a 301.

Ref: django.shortcuts.redirect


5. get_object_or_404(): Not Only for Models

Most people know this one, but not everyone knows it accepts a QuerySet or a Manager, not just a model class:

1
2
3
4
5
6
7
8
9
10
from django.shortcuts import get_object_or_404

# Common
article = get_object_or_404(Article, slug=slug)

# Recommended when you need restrictions or optimizations
article = get_object_or_404(
    Article.objects.filter(author=request.user).select_related("author"),
    slug=slug,
)

The second form makes sure a user can only open their own articles, and loads the author in the same query. A missing or foreign article both return 404, which avoids leaking which IDs exist.

Its sibling, get_list_or_404(), raises 404 when the filtered list is empty.

Ref: get_object_or_404()


6. format_html(): Safe HTML in Python Code

When you build HTML in Python (admin columns, template tags, model methods), it is tempting to use f-strings with mark_safe():

1
2
3
4
5
from django.utils.safestring import mark_safe

# Unsafe: user input is not escaped
def author_link(user):
    return mark_safe(f'<a href="/users/{user.pk}/">{user.username}</a>')

If a username contains <script>, it runs in the browser. format_html() escapes every argument before inserting it:

1
2
3
4
5
from django.utils.html import format_html

# Safe: arguments are escaped
def author_link(user):
    return format_html('<a href="/users/{}/">{}</a>', user.pk, user.username)
1
2
format_html('<a href="{}">{}</a>', "/u/1/", "<script>x</script>")
# '<a href="/u/1/">&lt;script&gt;x&lt;/script&gt;</a>'

Rule of thumb: use format_html() with placeholders, and never pass pre-built f-strings into it, because the f-string is already formatted before escaping can happen.

Ref: django.utils.html.format_html


7. cached_property: Compute Once per Instance

1
2
3
4
5
6
7
from django.utils.functional import cached_property


class Order(models.Model):
    @cached_property
    def total(self):
        return sum(item.price * item.quantity for item in self.items.all())

The first access to order.total runs the query and calculation. Every later access on the same instance returns the stored value.

This is useful in templates, where the same property may be accessed several times:

1
2
3
{% if order.total > 0 %}
  Total: {{ order.total }}
{% endif %}

With a normal @property, that template runs the query twice.

Gotcha: stale values

The cache lives as long as the instance. If the data changes, the cached value does not:

1
2
3
order.total          # 100
order.items.create(price=50, quantity=1)
order.total          # still 100

To reset it, delete the attribute: del order.total.

Python also has functools.cached_property. Both work similarly for most model use cases.

Ref: django.utils.functional.cached_property


8. signing: Tamper-Proof Tokens Without a Table

Need an unsubscribe link, an email confirmation link, or a short-lived token? You don’t always need a database table for it.

1
2
3
4
5
6
7
from django.core import signing

token = signing.dumps({"user_id": 42})
# 'eyJ1c2VyX2lkIjo0Mn0:1xOTPW:84v3GGVDGj...'

data = signing.loads(token, max_age=60 * 60 * 24)  # valid for 24 hours
# {'user_id': 42}

The token is signed with your SECRET_KEY. If anyone changes a single character, loads() raises signing.BadSignature. If the token is older than max_age, it raises signing.SignatureExpired.

1
2
3
4
5
6
7
8
9
10
11
from django.core import signing


def unsubscribe(request, token):
    try:
        data = signing.loads(token, max_age=60 * 60 * 24 * 30)
    except signing.BadSignature:  # also catches SignatureExpired
        return HttpResponseBadRequest("Invalid or expired link.")

    User.objects.filter(pk=data["user_id"]).update(newsletter=False)
    ...

Gotcha: signed is not encrypted

The payload is only base64 encoded. Anyone can decode it and read user_id: 42. Signing guarantees the data was not changed, not that it is hidden. Never put secrets or sensitive personal data in a signed token.

Ref: Cryptographic signing


Best Practices

  • Check django.utils and django.shortcuts before writing a new helper.
  • Use slugify(..., allow_unicode=True) when your content is not in English.
  • Use get_random_string() instead of random for anything security related.
  • Pass request to render_to_string() when templates rely on context processors.
  • Prefer redirect(instance) with get_absolute_url() to keep URL logic in one place.
  • Pass a filtered QuerySet to get_object_or_404() to enforce ownership.
  • Build HTML with format_html(), not f-strings with mark_safe().
  • Use cached_property for expensive per-instance calculations, and remember it can go stale.
  • Use signing for links and short-lived tokens, never for secrets.

Conclusion

Django is not only an ORM and a request cycle. It is also a toolbox of small, battle-tested functions that cover problems every project faces.

Before adding another function to your utils.py, check whether Django already solved it. The built-in version is usually more secure, already tested, and familiar to the next developer who reads your code.

Further Reading

This post is licensed under CC BY 4.0 by the author.