Home » Django » Make the first letter uppercase inside a django template

Make the first letter uppercase inside a django template

Posted by: admin November 30, 2017 Leave a comment

Questions:

I am pulling a name from a database which is stored as myname. How do I display this inside a Django template as Myname, with the first letter being in uppercase.

Answers:

Using Django built-in template filter called title

{{ "myname"|title }}

Questions:
Answers:

I know it’s a bit late, but you can use capfirst:

{{ "waiting for action"|capfirst }}

This will result into “Waiting for action”

Questions:
Answers:

The title filter works fine, but if you have a many-words string like: "some random text", the result is going to be "Some Random Text". If what you really want is to uppercase only the first letter of the whole string, you should create your own custom filter.

You could create a filter like this (follow the instructions on how to create a custom template filter from this doc – it’s quite simple):

# yourapp/templatetags/my_filters.py
from django import template

register = template.Library()

@register.filter()
def upfirstletter(value):
    first = value[0] if len(value) > 0 else ''
    remaining = value[1:] if len(value) > 1 else ''
    return first.upper() + remaining

Then, you should load the my_filters file at your template, and use the filter defined there:

{% load my_filters %}

...
{{ myname|upfirstletter }}