django学习之- json序列化

序列化操作
- Errordict
- 自定义Encoder
- django的模块可以直接序列化
第一种:
from django.core import serializers # 通过这个模块对queryset对象可以直接序列化
ret = models.tb.objects.all()
data = serializers.serialize("json",ret) #这里指定将ret序列化为json
第二种:
ret = models.tb.objects.values('id','name')
v = list(ret)
json.dumps(v)
这样不可以对时间序列化,如果要序列化时间,序号使用json.dumps(v,cls=JsonCustomEncoder(说明这个需要自定制))

实例:通过ajax提交前端表单数据到后台,后台通过form表单进行验证,如果有错误,通过重写类进行一次json序列化返回给前台

html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
<form id="loginform">
    {% csrf_token %}
    <input type="text" name="username" />
    <input type="password" name="pwd" />
    <a id="sub">提交</a>
</form>
<script src="/static/jquery-1.12.4.min.js"></script>
<script>
    $(function () {
        $('#sub').click(function () {
            $.ajax({
                url:'/app04/login',
                type:'POST',
                data:$('#loginform').serialize(),
                success:function (data) {
                    console.log(data);
                    arg = JSON.parse(data)
                },
                error:function () {
                    console.log(data)
                }
            })
        })
        }
            )
</script>
</body>
</html>
View Code

python代码

from django.shortcuts import render,HttpResponse
import json
from django import forms
from django.forms import fields,widgets
class logform(forms.Form):
    username = fields.CharField()
    pwd = fields.CharField(
        max_length=64,
        min_length=12
    )

from django.core.exceptions import ValidationError
class JsonCustomEncoder(json.JSONEncoder):
    '''重写此类,可以解决以下出现的2次序列化的问题,通过这个类可以一次性序列化'''
    def default(self, field):
        if isinstance(field,ValidationError):
            return {'code':field.code,'messages':field.messages}
        else:
            return json.JSONEncoder.default(self,field)

def login(request):
    if request.method == 'GET':
        return render(request,'app04/login.html')
    if request.method == 'POST':
        ret = {'status':True,'error':None,'data':None}
        out = logform(request.POST)
        if out.is_valid():
            print(out.cleaned_data)
        else:
            ret['error'] = out.errors.as_data()
            print(ret)
            result = json.dumps(ret,cls=JsonCustomEncoder) 
            return HttpResponse(result)    
View Code

 

posted @ 2017-12-21 23:56  十年如一..bj  阅读(1220)  评论(0编辑  收藏  举报