我有一个Django表单,该人需要添加他们的详细信息以进行订阅,并且我希望页面在Submit按钮下方显示成功的提交消息几秒钟(让我们说3),然后它应该消失并且表单字段应该显示为空。
views.py中的函数定义如下:
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})
Django模板:
{% 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>
当前代码有助于显示成功提交的消息以及空白表单字段,但不会使其消失。 有人可以帮忙吗?
答案 0 :(得分:1)
我建议您使用jQuery使消息消失并使表单为空,
<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>