[Django]-Make the first letter uppercase inside a django template

299👍

Using Django built-in template filter called title

{{ "myname"|title }}

185👍

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

{{ "waiting for action"|capfirst }}

This will result into "Waiting for action"

33👍

This solution also works if you have multiple words (for example all caps):

{{ "ALL CAPS SENTENCE"|lower|capfirst }}

This will output “All caps sentence”.

8👍

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 }}

6👍

It worked for me in template variable.

{{ user.username|title }}

If the user is “al hasib” then the it will return “Al Hasib”

or

{{ user.username|capfirst }}

If user is ‘hasib’ then the last one will return “Hasib”

Both look something like same but there’s some differences.

👤hasib

5👍

use
{{"myname"|title}}
this will make the fist letter of each word capital

2👍

Just use {{myname | capfirst}}
In Django the template filter capfirst capatialize the first letter of a given string.

Leave a comment