Make the first letter uppercase inside the django template

I pull the name from the database, which is stored as myname . How to display this inside a Django template as myname , with the first letter in uppercase.

+90
django django-templates
Jan 10 '13 at 22:20
source share
5 answers

Using the built-in Django template filter called title

 {{ "myname"|title }} 
+163
Jan 10 '13 at 22:23
source share

I know this a bit later, but you can use capfirst :

 {{ "waiting for action"|capfirst }} 

This will result in a "Pending Action"

+107
May 24 '13 at 8:29
source share

This solution also works if you have multiple words (e.g. all uppercase letters):

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

This will display "All caps."

+10
Mar 19 '18 at 11:52
source share

The title filter works fine, but if you have a lot of words, for example: "some random text" , the result will be "some random text" . If what you really want is the uppercase only first letter of the entire line, you must create your own custom filter.

You can create such a filter (follow the instructions to create a custom template filter from this doc - it's pretty 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 into your template and use the filter specified there:

 {% load my_filters %} ... {{ myname|upfirstletter }} 
+8
Jan 11 '13 at 2:48
source share

This worked for me in a template variable.

 {{ user.username|title }} 

If the user is Al-Hasib, he returns Al-Hasib

.or

 {{ user.username|capfirst }} 

If the user has the value 'hasib', then the latter will return "Hasib"

Both look pretty much the same, but there are some differences.

0
Aug 20 '19 at 13:39 on
source share



All Articles