http://www.cnblogs.com/wupeiqi/articles/6144178.html
Form组件
- form表单(验证;保留上次内容)
-
- Ajax(验证;无需上次内容)
- 返回HttpResponse
- 前端:跳转或错误信息
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError class AjaxForm(forms.Form): username = fields.CharField() user_id = fields.IntegerField( widget=widgets.Select(choices=[(0,'alex'),(1,'刘皓宸'),(2,'杨建'),]) ) # 自定义方法 clean_字段名 # 必须返回值self.cleaned_data['username'] # 如果出错:raise ValidationError('用户名已存在') def clean_username(self): v = self.cleaned_data['username'] if models.UserInfo.objects.filter(username=v).count(): # 整体错了 # 自己详细错误信息 raise ValidationError('用户名已存在') return v def clean_user_id(self): return self.cleaned_data['user_id'] def ajax(request): if request.method == 'GET': obj = AjaxForm() return render(request,'ajax.html',{'obj':obj}) else: ret = {'status':'NG','message':None} import json obj = AjaxForm(request.POST) if obj.is_valid(): # 跳转到百度 # return redirect('http://www.baidu.com') # if .... # obj.errors['username'] = ['用户名已经存在',] # if .... # obj.errors['email'] = ['用户名已经存在',] ret['status'] = 'OK' return HttpResponse(json.dumps(ret)) else: # print(type(obj.errors)) # print(obj.errors) from django.forms.utils import ErrorDict # print(obj.errors.as_ul()) # print(obj.errors.as_json()) # print(obj.errors.as_data()) ret['message'] = obj.errors # 错误信息显示在页面上 return HttpResponse(json.dumps(ret))
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="fm" method="POST" action="/ajax/"> {% csrf_token %} {{ obj.as_p }} <input type="button" value="Ajax提交" id="btn" /> </form> <script src="/static/jquery-3.1.1.js"></script> <script> $(function () { $('#btn').click(function () { $.ajax({ url: '/ajax/', type: 'POST', data: $('#fm').serialize(), dataType: 'JSON', success:function (arg) { // arg: 状态,错误信息 if (arg.status == 'OK'){ window.location.href = "http://www.baidu.com" } console.log(arg); } }) }) }) </script> </body> </html>
1. Form组件扩展:
1.简单扩展 利用Form组件自带的正则扩展: a. 方式一 from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.validators import RegexValidator class MyForm(Form): user = fields.CharField( error_messages={'invalid': '...'}, validators=[RegexValidator(r'^[0-9]+$', '请输入数字'), RegexValidator(r'^159[0-9]+$', '数字必须以159开头')], ) b. 方式二 from django.forms import Form from django.forms import widgets from django.forms import fields from django.core.validators import RegexValidator class MyForm(Form): user = fields.RegexField(r'^[0-9]+$',error_messages={'invalid': '...'})
2.基于源码流程 a. 单字段 from django.core.exceptions import NON_FIELD_ERRORS, ValidationError class AjaxForm(forms.Form): username = fields.CharField() user_id = fields.IntegerField( widget=widgets.Select(choices=[(0,'alex'),(1,'刘皓宸'),(2,'杨建'),]) ) # 自定义方法 clean_字段名 # 必须返回值self.cleaned_data['username'] # 如果出错:raise ValidationError('用户名已存在') def clean_username(self): v = self.cleaned_data['username'] if models.UserInfo.objects.filter(username=v).count(): # 整体错了 # 自己详细错误信息 raise ValidationError('用户名已存在') return v def clean_user_id(self): return self.cleaned_data['user_id'] b. 整体错误验证 class AjaxForm(forms.Form): username = fields.CharField() user_id = fields.IntegerField( widget=widgets.Select(choices=[(0,'alex'),(1,'刘皓宸'),(2,'杨建'),]) ) # 自定义方法 clean_字段名 # 必须返回值self.cleaned_data['username'] # 如果出错:raise ValidationError('用户名已存在') def clean_username(self): v = self.cleaned_data['username'] if models.UserInfo.objects.filter(username=v).count(): # 整体错了 # 自己详细错误信息 raise ValidationError('用户名已存在') return v def clean_user_id(self): return self.cleaned_data['user_id'] def clean(self): value_dict = self.cleaned_data v1 = value_dict.get('username') v2 = value_dict.get('user_id') if v1 == 'root' and v2==1: raise ValidationError('整体错误信息') return self.cleaned_data PS: _post_clean 2. Django序列化 a.对象 b.字典 c.元祖
2. Django序列化
from django.shortcuts import render from django.shortcuts import HttpResponse from app01 import models import json def xuliehua(request): return render(request,'xuliehua.html') """ def get_data(request): user_list = models.UserInfo.objects.all() return render(request,'get_data.html',{'user_list':user_list}) """ def get_data(request): from django.core import serializers ret = {'status':True,'data':None} try: # user_list = models.UserInfo.objects.all() # QuerySet【obj,obj,obj】 # ret['data'] = serializers.serialize("json",user_list) # // var # v = JSON.parse(arg.data); # // console.log(v); # user_list = models.UserInfo.objects.all().values('id','username') # ret['data'] = list(user_list) # console.log(arg.data); # user_list = models.UserInfo.objects.all().values_list('id', 'username') # ret['data'] = list(user_list) # console.log(arg.data); pass except Exception as e: ret['status'] = False result = json.dumps(ret) return HttpResponse(result)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用户列表</h1> <table id="tb"> </table> <script src="/static/jquery-3.1.1.js"></script> <script> $(function () { initData(); }); function initData() { $.ajax({ url :'/get_data/', type:'GET', dataType:'JSON', success:function (arg) { //$('#tb').append(arg); if(arg.status){ console.log(arg.data); //var v = JSON.parse(arg.data); //console.log(v); } } }) } </script> </body> </html>