Django学习系列之Form表单和ajax
Posted 差点点温柔
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django学习系列之Form表单和ajax相关的知识,希望对你有一定的参考价值。
Forms结合ajax
Forms的验证流程:
- 定义用户输入规则的类,字段的值必须等于html中name属性的值(pwd= forms.CharField(required=True)=<input type="password" name="pwd"/>,也就是说pwd=pwd)
- 把用户提交的数据交给规则的类处理
- 规则的类会判断用户输入的内容是否符合定义的规则
- 如果正确就把用户输入的内容以字典的形式存储,否则把报错信息以字典的形式存储
简单的Django-Form表单验证
定义urls.py
from django.conf.urls import url from django.contrib import admin from cmdb import views urlpatterns = [ url(r\'^login/\', views.login), ]
定义views.py
from django.shortcuts import render from django.shortcuts import HttpResponse import json from django import forms #定义用户输入的规则 class LoginForm(forms.Form): user = forms.CharField(required=True) #定义login.html中input标签中name=user的标签规则 pwd = forms.CharField(required=True) #定义login.html中input标签中name=pwd的标签规则 def login(request): if request.method == \'POST\': obj = LoginForm(request.POST) #把login.html中用户输入的内容封装到LoginForm类交给它处理 ret = obj.is_valid() #如果提交的数据符合LoginForm中的规则,则返回True,否则返回False if ret: print(obj.clean()) #如果符合规则以字典的形式打印出用户提交的数据 else: print(obj.errors) #如果不符合规则以字典的形式打印出错误 return render(request,\'login.html\')
定义login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div> <div> <input type="text" name="user"/> </div> <div> <input type="password" name="pwd"/> </div> <input type="button" value="提交" onclick="DoSubmit();"/> </div> <script src="/static/jquery-1.12.4.js"></script> <script> var input_dict = {}; function DoSubmit() { $("input").each(function () { #相当于for循环所有input标签 var v = $(this).val(); #获取循环到当前input标签的内容 var n = $(this).attr(\'name\'); #获取循环到当前input标签的属性值,name=user,user就是属性值,name=pwd,pwd就是属性值 input_dict[n] = v; #生成字典:{\'属性值\':\'标签输入的内容\'},{\'pwd\':111} }); console.log(input_dict); $.ajax({ url:\'/login/\', type:\'POST\', data:input_dict, success:function (data) { console.log(data); }, error:function () { } }) } </script> </body> </html>
ModelForm结合ajax
需求:
修改个人信息,如果有字段没填写就报错,如果字段填写没问题就保存到数据库
urls.py
url(r\'^info/$\',views.UserInfoView.as_view(),name=\'user_info\'),
models.py
class UserProfile(AbstractUser): nick_name = models.CharField(max_length=50,verbose_name=\'昵称\',default=\'\') birday = models.DateField(null=True,blank=True,verbose_name=\'生日\') choice_gender = ( ("male","男"), ("female","女"), ) gender = models.CharField(choices=choice_gender,default=\'female\',max_length=6,verbose_name=\'性别\') address = models.CharField(max_length=100,default=\'\',verbose_name=\'地址\') mobile = models.CharField(max_length=11,null=True,blank=True,verbose_name=\'手机号\') image = models.ImageField(upload_to=\'image/%Y/%m\',default=\'image/default.png\',max_length=100) class Meta: verbose_name = "用户信息" verbose_name_plural = "用户信息" def __str__(self): return self.username
forms.py
from users.models import * class UserInfoForm(forms.ModelForm): class Meta: model = UserProfile fields = [\'nick_name\',\'birday\',\'gender\',\'address\',\'mobile\']
views.py
class UserInfoView(LoginRequiredMixin,View): def get(self,request): return render(request,\'usercenter-info.html\',{}) def post(self,request): res = dict() userinfo = UserInfoForm(request.POST,instance=request.user) if userinfo.is_valid(): userinfo.save() res[\'status\'] = \'success\' else: res = userinfo.errors print(json.dumps(res)) # 假如address字段信息未填写,报错信息是这样的: "address": ["这个字段是必填项"]} return HttpResponse(json.dumps(res),content_type=\'application/json\')
userinfo.html
<form class="perinform" id="jsEditUserForm" autocomplete="off"> <ul class="right"> <li>昵 称: <input type="text" name="nick_name" id="nick_name" value="{{ request.user.nick_name }}" maxlength="10"> <i class="error-tips"></i> </li> <li>生 日: <input type="text" id="birth_day" name="birday" value="{{ request.user.birday }}" readonly="readonly"/> <i class="error-tips"></i> </li> <li>性 别: <label> <input type="radio" name="gender" value="male" {% ifequal request.user.gender \'male\' %}checked{% endifequal %} >男</label> <label> <input type="radio" name="gender" value="female" {% ifequal request.user.geder \'female\' %}checked{% endifequal %}>女</label> </li> <li class="p_infor_city">地 址: <input type="text" name="address" id="address" placeholder="请输入你的地址" value="{{ request.user.address }}" maxlength="10"> <i class="error-tips"></i> </li> <li>手 机 号: <input type="text" name="mobile" id="mobile" placeholder="请输入你的手机号码" value="{{ request.user.mobile|default_if_none:\'\' }}" maxlength="10"> </li> <li>邮 箱: <input class="borderno" type="text" name="email" readonly="readonly" value="{{ request.user.email }}"/> <span class="green changeemai_btn">[修改]</span> </li> <li class="button heibtn"> <input type="button" id="jsEditUserBtn" value="保存"> </li> </ul> {% csrf_token %} </form> $(\'#jsEditUserBtn\').on(\'click\', function(){ var _self = $(this), $jsEditUserForm = $(\'#jsEditUserForm\') verify = verifySubmit( [ {id: \'#nick_name\', tips: Dml.Msg.epNickName, require: true} ] ); if(!verify){ return; } $.ajax({ cache: false, type: \'post\', dataType:\'json\', url:"/users/info/", data:$jsEditUserForm.serialize(), #把form表单填写的内容序列化成json async: true, beforeSend:function(XMLHttpRequest){ _self.val("保存中..."); _self.attr(\'disabled\',true); }, success: function(data) { if(data.nick_name){ _showValidateError($(\'#nick_name\'), data.nick_name); #假如nick_name字段未填写报错是这样的:{"nick_name":{"这个字段是必填项"}},所以如果nick_name字段有报错就能获取到报错信息然后展示,birth_dat字段也同理, }else if(data.birday){ _showValidateError($(\'#birth_day\'), data.birday); }else if(data.address){ _showValidateError($(\'#address\'), data.address); }else if(data.status == "failure"){ Dml.fun.showTipsDialog({ title: \'保存失败\', h2: data.msg }); }else if(data.status == "success"){ Dml.fun.showTipsDialog({ title: \'保存成功\', h2: \'个人信息修改成功!\' }); setTimeout(function(){window.location.href = window.location.href;},1500); } }, complete: function(XMLHttpRequest){ _self.val("保存"); _self.removeAttr("disabled"); } }); });
效果
以上是关于Django学习系列之Form表单和ajax的主要内容,如果未能解决你的问题,请参考以下文章