直接上代码:
HTML,由Form插件自动生成input标签
Ajax提交Form验证
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),
]