Registering Custom Tags

The Django Messages Framework provides default tags for common scenarios, but there are times when you may need to define your own cus…

" />
×
   ❮   
PYTHON FOR DJANGO DJANGO FOR BEGINNERS DJANGO SPECIFICS PAYMENT INTEGRATION API BASICS Roadmap
     ❯   

MESSAGES FRAMEWORK

Custom Message tags

Registering Custom Tags

The Django Messages Framework provides default tags for common scenarios, but there are times when you may need to define your own custom tags. Custom tags allow you to tailor messages to specific situations or to integrate seamlessly with CSS frameworks or design themes. This flexibility ensures that your application's feedback messages align with your brand or UI requirements.

Why Create Custom Tags?

While the default tags (info, success, warning, error, etc.) cover most use cases, there might be scenarios where additional levels of categorization are needed. For instance, you may want to define tags like critical, notice, or validation_error. By registering custom tags, you can ensure that these new categories get consistent styling and behavior across your application.

Approaches to Registering Custom Tags

There are two primary ways to register custom tags in Django:

  1. Using extra_tags when adding a message.
  2. Modifying MESSAGE_TAGS in settings.py for new tags.

1. Using extra_tags

The simplest way to add a custom tag to a message is by passing the extra_tags argument. This approach does not replace the built-in tags but adds custom labels that can be used for further styling or identification. Here’s an example:

from django.contrib import messages

def notify_user(request):
    messages.add_message(
        request, 
        messages.WARNING, 
        'This is a critical warning!',
        extra_tags='critical'
    )

In this example, the extra_tags adds the tag critical to the warning message. This means you can customize the CSS styles for critical warnings separately.

Template Example:

Here’s how you can use these tags in your template to customize the display:

<!-- Template code -->
{% if messages %}
    <div class="container mt-3">
        {% for message in messages %}
            <div class="alert alert-{{ message.tags }} {{ message.extra_tags }} alert-dismissible fade show" role="alert">
                {{ message }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        {% endfor %}
    </div>
{% endif %}

2. Modifying MESSAGE_TAGS in settings.py

Another method to register custom tags is by modifying the MESSAGE_TAGS dictionary in your settings.py file. This is useful when you want to create entirely new message levels beyond the default ones. By doing this, your custom tags are treated just like the built-in tags, making them more integrated with the existing framework.

Step 1: Define Custom Levels

Before adding new tags, you need to define custom message levels. Django provides constants for the default levels, but you can define your own as integers:

from django.contrib.messages import constants as message_constants

# Define a new custom level
CRITICAL = 50

Step 2: Register Custom Levels in settings.py

After defining the custom level, register it in MESSAGE_TAGS:

# settings.py

from django.contrib.messages import constants as message_constants

MESSAGE_TAGS = {
    message_constants.DEBUG: 'debug',
    message_constants.INFO: 'info',
    message_constants.SUCCESS: 'success',
    message_constants.WARNING: 'warning',
    message_constants.ERROR: 'error',
    50: 'critical'  # Adding custom level
}

Step 3: Using the Custom Tag in Your View

You can now use the new custom level in your views:

from django.contrib import messages

def custom_alert_view(request):
    messages.add_message(request, 50, 'Critical system failure! Please contact support.')

Step 4: Applying Custom CSS Styles

Finally, apply CSS styles in your template based on the custom tags:

<!-- Template code -->
{% if messages %}
    <div class="container mt-3">
        {% for message in messages %}
            <div class="alert alert-{{ message.tags }} alert-dismissible fade show" role="alert">
                {{ message }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        {% endfor %}
    </div>
{% endif %}

In your CSS:

.alert-critical {
    background-color: #ff4d4d;  /* Red background for critical alerts */
    color: #fff;  /* White text */
    border: 1px solid #cc0000;  /* Dark red border */
}

Conclusion

Registering custom tags in Django allows you to extend the default messaging functionality, offering more precise feedback for users. By either adding extra_tags or modifying MESSAGE_TAGS, you can ensure that your custom messages maintain a consistent look and feel. Understanding how to create and apply these customizations is essential for building user-friendly and visually consistent web applications.


Django-tutorial.dev is dedicated to providing beginner-friendly tutorials on Django development. Examples are simplified to enhance readability and ease of learning. Tutorials, references, and examples are continuously reviewed to ensure accuracy, but we cannot guarantee complete correctness of all content. By using Django-tutorial.dev, you agree to have read and accepted our terms of use , cookie policy and privacy policy.

© 2024 Nischal Lamichhane. All Rights Reserved.
Django-tutorial.dev is styled using Bootstrap 5.
And W3.CSS.