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:

  1. Import the template module from the django package.
  2. Create a new instance of the template library using template.Library().
  3. Define a custom filter function named capitalize_first.
  4. Check if the input value is a non-empty string using isinstance and conditionals.
  5. If the input is a valid string, capitalize the first character using string slicing and concatenation.
  6. If the input is not a valid string, return the original value.
  7. Register the custom filter function with the template library using register.filter('capitalize_first', capitalize_first).
  8. In your Django template, load the custom template library using {% load your_app_name %} where your_app_name is the name of your Django app.
  9. Use the custom filter in your template by applying it to the desired variable with {{ your_variable|capitalize_first }}.