Make success message disappear after few seconds of django form submission and display empty form

Viewed 1836

I have a Django form where the person needs to add their details to subscribe and I want the page to show successful submission message below the submit button for few seconds (lets say 3) and then it should disappear and the form fields should be displayed empty.

The function definition in views.py is as follows :

def new_customer(request):
    if request.method == "POST":
        form = customer_form(request.POST)

        if form.is_valid():
            form.save() 
            messages.add_message(request, message_constants.SUCCESS, '✔️ SUCCESSFUL SUBSCRIPTION')

            return HttpResponseRedirect('http://127.0.0.1:8000/subscribe/')

    else:
        form = customer_form()
    return render(request,"new_customer.html",{'form':form})

The Django template :


{% load static %}
<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Subscribe</title>
    <link href="https://fonts.googleapis.com/css?family=Poppins&display=swap" rel="stylesheet">
    <link href="{% static "nav.css" %}" rel="stylesheet">
    <link href="{% static "form.css" %}" rel="stylesheet">

</head>
{% include "navbar.html" %}
<body>

<form method="POST" class="post-form" enctype="multipart/form-data">{% csrf_token %}  
        {{ form.as_p }}  
        <button type="submit" class="btn">Subscribe</button>  
        {% if messages %}
        <ul id ="successMessage" class="messages">
            {% for message in messages %}
            <li{% if message.tags %} class="{{ message.tags }}"{% endif %} style="color:green; font-size: 20px; list-style-type: none;">{{ message }}</li>
            {% endfor %}
        </ul>


        {% endif %}
</form>  

</body>  
</html>  

The current code helps display the message for successful submission, as well as empty form fields but does not make it disappear. Could anyone help ?

1 Answers

I suggest you use jQuery to make messages disappear and make form empty,

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>

<script text="javascript">
    setTimeout(fade_out, 3000);
    function fade_out() {
        $(".messages").fadeOut().empty();
    }
    $(".post-form")[0].reset(); // this is to reset the form 
</script>
Related