Episode 6 of 13

Displaying Feedback

Learn about Displaying Feedback

Why User Feedback Matters

When users perform actions like creating, updating, or deleting a contact, they need visual feedback that their action was successful. Without it, users are left wondering if anything happened. Django's messages framework provides a perfect way to display these notifications.

Setting Up Django Messages

Django's messages framework is enabled by default. It uses the django.contrib.messages module to store temporary messages that are displayed once and then removed. Common message levels include success, info, warning, and error.

Adding Messages to Views

In your views, import messages from django.contrib and use functions like messages.success(request, "Contact created successfully!") after performing an action. The message is stored in the request session and will be available in the next template render.

Displaying Messages in the Template

In your base.html template, add a section that loops through the messages and displays each one inside a styled alert div. Use DaisyUI's alert component classes (alert-success, alert-error, alert-warning) to color-code the messages based on their level.

HTMX and Out-of-Band Swaps

When HTMX replaces only a partial section of the page, normal Django messages would not appear because the base template is not re-rendered. To solve this, use HTMX's hx-swap-oob (out-of-band) attribute. Include a messages partial in your HTMX responses that targets the messages container, and set hx-swap-oob="true" so HTMX swaps it into the correct location regardless of the main swap target.

Auto-Dismissing Messages

Add a small amount of CSS or use DaisyUI's built-in toast component to position messages in a corner of the screen. Optionally, use a simple CSS animation to fade the messages out after a few seconds, giving users enough time to read the feedback before it disappears.