Using HTMX and Django to Show Toast Messages on Form Submission

Manjurul Hoque Rumi
Django Unleashed
Published in
3 min readMay 29, 2024

In our application, we need to show toast message to the users instead of loading full page. If we have a django application where user can submit a form and we have to show success or warning message to the users. We could implement a API and call via fetch or ajax and show toast message which will take time to implement on client side.

Introduction

HTMX is a library that allows you to access modern browser features directly from HTML, making it easier to enhance user interfaces with minimal JavaScript. Toastr.js is a simple JavaScript library for showing non-blocking notifications.

Prerequisites

  • Basic knowledge of Django
  • Familiarity with HTMX and JavaScript
  • Django application set up and running

Views

Create a view to handle form submission:

from django.shortcuts import render, redirect
from django.http import JsonResponse
from .forms import EducationForm


def update_education(request):
if request.method == 'POST':
form = EducationForm(request.POST)
if form.is_valid():
form.save()
response = JsonResponse({'success': True})
response['HX-Trigger'] = json.dumps({
"show-toast": {
"level": "success",
"title": "Success",
"message": "Education details updated successfully!"
}
})
return response
else:
response = JsonResponse({'success': False})
response['HX-Trigger'] = json.dumps({
"show-toast": {
"level": "error",
"title": "Error",
"message": "Failed to update education details!"
}
})
return response
else:
form = EducationForm()
return render(request, 'myapp/education_form.html', {'form': form})

URL Configuration

Add a URL pattern for the view:

from django.urls import path
from .views import update_education

urlpatterns = [
path('update-education/', update_education, name='update-education'),
]

HTML Template

Create a template for the form:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Education Form</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://unpkg.com/htmx.org@1.9.12"></script>
</head>
<body>
<div class="container">
<form id="education-data" hx-put="{% url 'update-education' %}" hx-include="#education-data" hx-disabled-elt="this" hx-swap="none">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary btn-sm pull-right">
<i class="fa fa-plus-circle"></i>
Update
</button>
</form>
</div>

<script>
// Add event listener for the 'show-toast' custom event
document.addEventListener('show-toast', event => {
const { level, message, title } = event.detail;
toastr[level](message, title);
});
</script>
</body>
</html>

The update_education view handles form submission. It validates the form and returns a JSON response with a custom header HX-Trigger containing the toast message details to trigger custom event we registered. The script listens for the show-toast custom event and displays a toast message using Toastr.js based on the event details.

Conclusion

By leveraging Django, HTMX, and Toastr.js, you can provide users with immediate feedback via toast messages without reloading the entire page. This approach enhances the user experience and reduces the complexity of client-side JavaScript code. HTMX simplifies the integration by handling AJAX requests and responses seamlessly, making it a powerful tool for modern web development.

--

--