1. 程式人生 > >django form表單驗證,使用Ajax提交併返回提示資訊(JSON傳遞資料)

django form表單驗證,使用Ajax提交併返回提示資訊(JSON傳遞資料)

直接上程式碼:

HTML,由Form外掛自動生成input標籤

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax提交Form驗證</title>

</head>
<body>

    <form action="/ajaxForm/" method="post" id="fm">
        {% csrf_token %}
        <p>username:{{ user.username }}<span id="username_span"></span></p>
        <p>gender:{{ user.gender }}<span id="gender_span"></span></p>
        <p><input type="button" value="Ajax提交" id="fm_submit"></p>
    </form>
    <script src="/static/jquery-3.3.1.min.js"></script>
    <script>

        $(function(){
            $("#fm_submit").click(function(){
                $.ajax({
                    url:"/ajaxForm/",
                    type:"post",
                    dataType:"JSON",
                    data:$("#fm").serialize(),
                    success:function(args){
                        if (args.status == "OK"){
                            window.location.href("Http://www.baidu.com")
                        }else if(args.status=="NG"){
                            console.log(args.msg)
                            $("#username_span").html(args.msg.username[0])
                        }
                    }
                })
             })
        })

    </script>

</body>
</html>

VIEWS程式碼

from django.shortcuts import render,redirect,HttpResponse
from django import forms
from django.forms import widgets
from app1 import models
import json

class AjaxForm(forms.Form):
    username = forms.CharField(
        required=True,
        min_length=3,
        error_messages={
            "min_length":"使用者名稱輸入不正確",
        }
    )
    gender = forms.BooleanField(
        widget=widgets.RadioSelect(choices=[(0,"男"),(1,"女"),]),
        required=False
    )

# Create your views here.
def ajaxForm(request):
    if request.method=="GET":
        user = AjaxForm()
        print("heheh ")
        return render(request,"AjaxForm.html",{"user":user})
    else:
        ret = {"status": "NG", "msg": None}
        af = AjaxForm(request.POST)
        if af.is_valid():
            print(af.cleaned_data)
            models.User.objects.create(**af.cleaned_data)
            ret["status"]="OK"
            return HttpResponse(json.dumps(ret))
        else:
            print("NG")
            ret["msg"] = af.errors
            return HttpResponse(json.dumps(ret))

MODELS資料庫表:

from django.db import models

# Create your models here.
class User(models.Model):
    username = models.CharField(max_length=50)
    gender = models.BooleanField()

 

URL路由:

from django.contrib import admin
from django.urls import path
from app1 import views

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