Make the first letter uppercase inside a django template

DjangoDjango Templates

Django Problem Overview


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.

Django Solutions


Solution 1 - Django

Using Django built-in template filter called title

{{ "myname"|title }}

Solution 2 - Django

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

{{ "waiting for action"|capfirst }}

This will result into "Waiting for action"

Solution 3 - Django

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

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

This will output "All caps sentence".

Solution 4 - Django

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

Solution 5 - Django

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.

Solution 6 - Django

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

Solution 7 - Django

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMayankView Question on Stackoverflow
Solution 1 - DjangoAamir RindView Answer on Stackoverflow
Solution 2 - DjangooblalexView Answer on Stackoverflow
Solution 3 - DjangoBjorn GarciaView Answer on Stackoverflow
Solution 4 - DjangoValdir Stumm JuniorView Answer on Stackoverflow
Solution 5 - DjangohasibView Answer on Stackoverflow
Solution 6 - DjangoRakesh GombiView Answer on Stackoverflow
Solution 7 - DjangoAmitha MohanView Answer on Stackoverflow