Best Practices for Reusable Modals in Django Templates

I’m working on a Django project where I need to include a delete confirmation modal in 10 different views (e.g., for deleting buildings, units, etc.). Each modal shares a similar structure but requires a unique warning message and action URL depending on the view.

I know I can simply copy and paste the modal code into each template, but I’m curious about the best design practices for handling this situation, especially when it comes to maintainability and clarity.

I’ve considered the following approaches:

  1. Using a Partial Template: Creating a reusable partial template for the modal and passing the dynamic content (URL, warning message) from the view.
  2. Defining the Modal in Each Template: Copying the modal structure into each template and customizing the content for each case.
  3. Using Template Inheritance: Defining a base modal template with blocks for the message and URL, which can be overridden in each child template.

I’m also aware that by abstracting some of the styling concerns into Tailwind components (like buttons and modals), I’ve separated some consistency concerns, but I’m still curious about the best approach from a design and maintainability perspective.

Given that the modal needs to be consistent across the app but with different content, what would be considered the best practice here? How do you balance reusability, clarity, and maintainability in such scenarios? Would love to hear your insights!

I’d go for a partial template or use one of the many Django component libraries (django-cotton, django-viewcomponent, django-components, …) depending on how many and how complicated your reusable components will be.

1 Like

Appreciate the suggestions! I’ve tried some of those Django component libraries before, but they didn’t quite click with me. I’ll take another look into them though.

Right now, I’m leaning towards partial templates because they seem the fit best. My only hang-up is passing a paragraph of text through context—it feels a bit awkward for something so simple.

Usually, I don’t deal with modals directly in the template. I’ve been using HTMX to load views into modals, which lets me grab data with a GET request and then handle the POST. But in this project, they’re sticking with standard class-based delete views where the modal is already in the template, so it’s a bit different from what I’m used to.

Thanks again for the ideas!