标签:encode style except .ajax 对象 char 通过 mencoder 信息
关于Django中的序列化主要应用在数据库中检索的数据返回给客户端用户,特别的Ajax请求一般返回的为JSON格式
这是django内建的序列器,它可以很好的序列化QuerySet,但当他遇到单独的django model object时就会报错,并且它序列化出的model中如果包含DateTimeField时,输出数据中的时间是个datetime对象,无法直接当作序列化数据使用
from django.core import serializers ret = models.BookType.objects.all() data = serializers.serialize("json", ret)
import json # ret = models.BookType.objects.all().values("caption") ret = models.BookType.objects.all().values_list("caption") ret = list(ret) result = json.dumps(ret)
import json from datetime import date from datetime import datetime class JsonCustomEncoder(json.JSONEncoder): def default(self, field): if isinstance(field, datetime): return o.strftime(‘%Y-%m-%d %H:%M:%S‘) elif isinstance(field, date): return o.strftime(‘%Y-%m-%d‘) else: return json.JSONEncoder.default(self, field) # ds = json.dumps(d, cls=JsonCustomEncoder)
#!/usr/bin/env python # _*_ coding:utf-8 _*_ # Author: JiaChen from django.shortcuts import render, HttpResponse, redirect from django import forms from django.forms import widgets from django.forms import fields import json class LoginForm(forms.Form): username = fields.CharField() password = fields.CharField( max_length=64, min_length=12 ) from django.core.exceptions import ValidationError class JsonCustomEncoder(json.JSONEncoder): 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, "login.html") elif request.method == "POST": ret = {"status": True, "error": None, "data": None} obj = LoginForm(request.POST) if obj.is_valid(): print(obj.cleaned_data) else: ret["error"] = obj.errors.as_data() result = json.dumps(ret, cls=JsonCustomEncoder) return HttpResponse(result)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="fm"> {% csrf_token %} <p><input type="text" name="username"></p> <p><input type="password" name="password"></p> <a id="submit">提交</a> </form> <script src="/static/jquery-1.12.4.js"></script> <script> $(function () { $("#submit").click(function () { $.ajax({ url: "/login.html", type: "POST", data: $("#fm").serialize(), success: function (arg) { console.log(arg); arg = JSON.parse(arg); }, error: function () { } }) }); }); </script> </body> </html>
标签:encode style except .ajax 对象 char 通过 mencoder 信息
原文地址:http://www.cnblogs.com/qiang8216/p/7243185.html