django filter text first character upper case
# Import necessary module
from django import template
# Create a new instance of the template library
register = template.Library()
# Define a custom filter function
@register.filter(name='capitalize_first')
def capitalize_first(value):
# Check if the value is a string and not empty
if isinstance(value, str) and value:
# Capitalize the first character of the string
return value[0].upper() + value[1:]
else:
# Return the original value if it's not a valid string
return value
# Register the filter function with the template library
register.filter('capitalize_first', capitalize_first)
In your Django template:
<!-- Load the custom template library -->
{% load your_app_name %}
<!-- Use the custom filter in your template -->
{{ your_variable|capitalize_first }}
Explanation:
- Import the
template
module from thedjango
package. - Create a new instance of the template library using
template.Library()
. - Define a custom filter function named
capitalize_first
. - Check if the input
value
is a non-empty string usingisinstance
and conditionals. - If the input is a valid string, capitalize the first character using string slicing and concatenation.
- If the input is not a valid string, return the original value.
- Register the custom filter function with the template library using
register.filter('capitalize_first', capitalize_first)
. - In your Django template, load the custom template library using
{% load your_app_name %}
whereyour_app_name
is the name of your Django app. - Use the custom filter in your template by applying it to the desired variable with
{{ your_variable|capitalize_first }}
.