zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    【Leetcode】【Easy】Remove Duplicates from Sorted List
    【Leetcode】【Easy】Pascal's Triangle II
    【Leetcode】【Easy】Pascal's Triangle
    【Leetcode】【Easy】Binary Tree Level Order Traversal II
    【Leetcode】【Easy】Binary Tree Level Order Traversal
    【Leetcode】【Easy】Maximum Depth of Binary Tree
    【Leetcode】【Easy】Minimum Depth of Binary Tree
    【Leetcode】【Easy】Balanced Binary Tree
    【Leetcode】【Easy】Symmetric Tree
    如何使用Action.Invoke()触发一个Storyboard
  • 原文地址:https://www.cnblogs.com/zy6103/p/8083079.html
Copyright © 2011-2022 走看看