已迁移-Django - form标签提交前的确认

before

场景就是,form表单中,直接点击如果按钮的类型是submit的话,那么点击就直接提交了。
我们如果想要做个确认啥的,如何实现呢?
来看示例。

代码示例

django3.2 + python3.9

urls.py

from django.contrib import admin
from django.urls import path
from api.views import  index

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', index),
]

views.py

from django.shortcuts import render


def index(request):
	if request.method == "GET":
		return render(request, 'index.html', {"user": ""})
	user = request.POST.get("user")
	print(user)
	return render(request, 'index.html', {"user": user})

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!-- 主要就是在form标签中指定 onsubmit="return sub()" return后面跟函数,当函数返回true,就执行提交,否则就不提交-->
<form action="" method="post" onsubmit="return sub()">
    {% csrf_token %}
    <input type="text" name="user" placeholder="user" class="form-control">
    <input type="submit" id="btn" value="提交">
    <span>{{ user }}</span>
</form>
</body>
<script>
    function sub() {
        // 确认弹出框
        let result = confirm('确认提交?')
        if (result == true) {
            return true;
        } else {
            return false
        }
    }
</script>
</html>

参考:https://blog.csdn.net/lanmanck/article/details/46355709

posted @ 2023-03-08 16:25  听雨危楼  阅读(30)  评论(0编辑  收藏  举报