Django and Htmx messages with refresh dataTables after submit form

I am a beginner in the django programming language who please need some assistance. I have a data which after validation of my form displays a success message: “Operation completed successfully” from the return httpReponse but does not refresh the page. However, by adding this script in the form tag, the dataTable is refreshed but success message is not displayed

views.py :

def index(request):
    all_person = Personne.objects.all()
    context = {'all_person': all_person}
    return render(request, 'index.html', context)

def add_personne(request):
    if request.method == "POST":
        form = PersonneForm(request.POST)
        if form.is_valid():
              form.save()
              return HttpResponse(status=204,
                                headers={'HX-Trigger': json.dumps({
                                         "personList": None,
                                        "showMessage": "Opération effectuée avec succès",
                                     })  
                                })
            
    else:
        form = PersonneForm()
    return render(request, 'form_personne.html', {'form':form})

<---------------------------- Début index.html ------------------------------------------->

index.html

    {% extends "base.html" %}

{% block title %}Tableau-Dynamique{% endblock title %}

{% block content %}

<div class="col md-12">
    <button type="button" class="btn btn-primary" hx-get="{% url 'add_personne' %}" hx-target="#dialog"
        style="width:300px;">
        Add New
    </button>

</div>
<br>
<h3 class="mt-3">Option de recherche</h3>

<!--HTML table with student data-->


<table id="tableID" class="display">
    <thead>
        <tr>
            <th class="px-2 py-2 text-center">N°</th>
            <th class="px-2 py-2 text-center">Nom</th>
            <th class="px-2 py-2 text-center">Age</th>
        </tr>
    </thead>

    <tbody>
        {% for personne in all_person %}
        <tr>
            <td>{{ forloop.counter }}</td>
            <td>{{personne.nom}}</td>
            <td>{{personne.age}}</td>
        </tr>
        {% endfor %}
    </tbody>
</table>


{% endblock content %}

{% block ScriptBlock %}

<script>
    $(document).ready(function () {

        var personDataTable = $("#tableID").DataTable({
            language: {
                "url": 'https://cdn.datatables.net/plug-ins/2.0.3/i18n/fr-FR.json'
            },

            "aLengthMenu": [[3, 5, 10, 25, -1], [3, 5, 10, 25, "All"]],
            "iDisplayLength": 3
        });

        
    });

    {% endblock ScriptBlock %}

<---------------------------- Fin index.html ------------------------------------------>

<!-- identification/templates/base.html  -->
{% load static %}

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}{% endblock %}</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" type="text/css"
        href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css" />


    <!-- DataTables CSS -->

    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.0/css/jquery.dataTables.min.css" />


</head>

<body>
    <div class="container">
        <div class="row">
            <h1 style="color: green;">Test sur tableau dynamique</h1>
            {% block content %}{% endblock %}
        </div>
    </div>


    <!-- DataTables cdn jquery -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.12.0/js/jquery.dataTables.min.js"></script>



    {% block ScriptBlock %}


    {% endblock ScriptBlock %}



    <!-- Placeholder for the modal -->
    <div id="modal" class="modal fade" tabindex="-1">
        <div id="dialog" class="modal-dialog" hx-target="this"></div>
    </div>


    <!-- Empty toast to show the message   -->
    <div class="toast-container position-fixed top-0 end-0 p-3">
        <div id="toast" class="toast align-items-center text-white bg-success border-0" role="alert"
            aria-live="assertive" aria-atomic="true">
            <div class="d-flex">
                <div id="toast-body" class="toast-body"></div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"
                    aria-label="Close"></button>
            </div>
        </div>
    </div>


    <!--     <script src="https://unpkg.com/htmx.org@1.9.10"></script> -->
    <script src="https://unpkg.com/htmx.org@1.9.10"
        integrity="sha384-D1Kt99CQMDuVetoL1lrYwg5t+9QdHe7NLX/SoJYkXDFfX37iInKRy5xLSi8nO7UC"
        crossorigin="anonymous"></script>

    <script src="{% static 'dialog.js' %}"></script>
    <script src="{% static 'toast.js' %}"></script>

    
</body>

</html>

Welcome @djidji2797 !

Side note: When posting code, templates, HTML, or error messages here, enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted. (I’ve taken the liberty of fixing your original post for you.)

In your index.html, I see a <script> tag but I don’t see the corresponding </script> tag. Is it in your file and just not copied to your post?

Also, you wrote:

I’m not understanding what you wrote here. What script are you talking about in what form tag?

You reference a template file named form_personne.html, what does it look like?

Thank you indeed you are right I copied the message from the “index.html” file incorrectly

index.html

<!-- identification/templates/index.html  -->

{% extends "base.html" %}

{% block title %}Tableau-Dynamique{% endblock title %}

{% block content %}

<div class="col md-12">
    <button type="button" class="btn btn-primary" hx-get="{% url 'add_personne' %}" hx-target="#dialog"
        style="width:300px;">
        Add New
    </button>

</div>
<br>
<h3 class="mt-3">Option de recherche</h3>

<!--HTML table with student data-->


<table id="tableID" class="display">
    <thead>
        <tr>
            <th class="px-2 py-2 text-center">N°</th>
            <th class="px-2 py-2 text-center">Nom</th>
            <th class="px-2 py-2 text-center">Age</th>
        </tr>
    </thead>

    <tbody>
        {% for personne in all_person %}
        <tr>
            <td>{{ forloop.counter }}</td>
            <td>{{personne.nom}}</td>
            <td>{{personne.age}}</td>
        </tr>
        {% endfor %}
    </tbody>
</table>


{% endblock content %}

{% block ScriptBlock %}

<script>
    $(document).ready(function () {

        var personDataTable = $("#tableID").DataTable({
            language: {
                "url": 'https://cdn.datatables.net/plug-ins/2.0.3/i18n/fr-FR.json'
            },

            "aLengthMenu": [[3, 5, 10, 25, -1], [3, 5, 10, 25, "All"]],
            "iDisplayLength": 3
        });

        
    });
</script>

{% endblock ScriptBlock %}

here is the file “form_personne.html”

form_personne.html

{% load widget_tweaks %}

{% block content %}
{% with WIDGET_ERROR_CLASS='is-invalid' %}
<!-- insert automatically data in dataTables with HTMX  <form hx-post="{{ request.path }}" class="modal-content" hx-on="htmx:afterRequest:location.reload()">
 -->
<form hx-post="{{ request.path }}" class="modal-content">
  {% csrf_token %}
  <div class="modal-header">
    <h5 class="modal-title">Fiche personne</h5>
    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
  </div>
  <div class="modal-body form-group required">
    <div class="mb-3">
      <label for="{{ form.nom.id_for_label }}" class="form-label control-label">Nom</label>
      {% render_field form.nom class="form-control" %}
      <div class="invalid-feedback">{{ form.nom.errors|first }}</div>
    </div>
    <div class="mb-3">
      <label for="{{ form.age.id_for_label }}" class="form-label control-label">Age</label>
      {% render_field form.age class="form-control" %}
      <div class="invalid-feedback">{{ form.age.errors|first }}</div>
    </div>
        
  <div class="modal-footer">
    
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
    
<button type="submit" class="btn btn-primary">Enregister</button>
</div>
</form>
{% endwith %}

{% endblock %}

Can you please elaborate on this?

I’m not understanding what you’re trying to describe here or what the issue(s) is (are). Please provide more details about what you’re trying to do, what you’re expecting to have happen, and what is actually happening.

I cannot update my tables after validating the form. I would like to refresh the tables and also display the following showMessage: “Operation completed successfully”

What happens when I validate the form the showMessage “Operation completed successfully” is displayed on the screen but does not update the form data in the table…

I don’t see you returning the new data to update the existing display.

When you make a request using HTMX, it’s expecting to receive HTML as a response. That HTML is going to replace the HTML tag making the request, unless the response is identified as containing an out-of-band response.

So if you want part of the HTML of your page updated, then you need to render the div for that data and return it as part of the HTML response.

I want to refresh the table that is in the index.html file after form validation.
By adding this script in the form tag the table which is found in the index.html file is automatically refreshed but the showMessage “Operation completed successfully” is not displayed.
But when I remove hx-on=“htmx:afterRequest:location.reload()” in the form tag the message “Operation completed successfully” appears on the screen and the table is not refreshed automatically so I refresh the page myself from the browser