Python开发【Django】:Form组件

半城伤御伤魂 提交于 2020-01-17 14:16:44

 Form组件

Django的Form主要具有一下几大功能:

  • 生成HTML标签
  • 验证用户数据(显示错误信息)
  • HTML Form提交保留上次提交数据
  • 初始化页面显示内容

创建Form类时,主要涉及到 【字段】 和 【插件】,字段用于对用户请求数据的验证,插件用于自动生成HTML;

1、内置字段

Field
    required=True,               是否允许为空
    widget=None,                 HTML插件
    label=None,                  用于生成Label标签或显示内容
    initial=None,                初始值
    help_text='',                帮助信息(在标签旁边显示)
    error_messages=None,         *错误信息 {'required': '不能为空', 'invalid': '格式错误'}
    show_hidden_initial=False,   是否在当前插件后面再加一个隐藏的且具有默认值的插件(可用于检验两次输入是否一直)
    validators=[],               *自定义验证规则 下面有介绍具体用法
    localize=False,              是否支持本地化
    disabled=False,              是否可以编辑
    label_suffix=None            Label内容后缀
 
*注:继承field的字段  field里面的参数都可以用
 
CharField(Field)                 
    max_length=None,             最大长度
    min_length=None,             最小长度
    strip=True                   是否移除用户输入空白
 
IntegerField(Field)
    max_value=None,              最大值
    min_value=None,              最小值
 
FloatField(IntegerField)
    ...
 
DecimalField(IntegerField)
    max_value=None,              最大值
    min_value=None,              最小值
    max_digits=None,             总长度
    decimal_places=None,         小数位长度
 
BaseTemporalField(Field)
    input_formats=None          时间格式化   
 
DateField(BaseTemporalField)    格式:2015-09-01
TimeField(BaseTemporalField)    格式:11:12
DateTimeField(BaseTemporalField)格式:2015-09-01 11:12
 
DurationField(Field)            时间间隔:%d %H:%M:%S.%f
    ...
 
RegexField(CharField)           *等同于CharField加上validators
    regex,                      自定制正则表达式
    max_length=None,            最大长度
    min_length=None,            最小长度
    error_message=None,         忽略,错误信息使用 error_messages={'invalid': '...'}
 
EmailField(CharField)      
    ...
 
FileField(Field)
    allow_empty_file=False     是否允许空文件 *上传文件
 
ImageField(FileField)      
    ...
    注:需要PIL模块,pip3 install Pillow
    以上两个字典使用时,需要注意两点:
        - form表单中 enctype="multipart/form-data"
        - view函数中 obj = MyForm(request.POST, request.FILES)
 
URLField(Field)
    ...
 
 
BooleanField(Field)  
    ...
 
NullBooleanField(BooleanField)
    ...
 
*ChoiceField(Field)            *单选下拉框
    ...
    choices=(),                选项,如:choices = ((0,'上海'),(1,'北京'),)
    required=True,             是否必填
    widget=None,               插件,默认select插件
    label=None,                Label内容
    initial=None,              初始值
    help_text='',              帮助提示
 
 
ModelChoiceField(ChoiceField)  *多选下拉框
    ...                        django.forms.models.ModelChoiceField
    queryset,                  # 查询数据库中的数据
    empty_label="---------",   # 默认空显示内容
    to_field_name=None,        # HTML中value的值对应的字段
    limit_choices_to=None      # ModelForm中对queryset二次筛选
     
ModelMultipleChoiceField(ModelChoiceField)
    ...                        django.forms.models.ModelMultipleChoiceField
 
 
     
TypedChoiceField(ChoiceField)
    coerce = lambda val: val   对选中的值进行一次转换
    empty_value= ''            空值的默认值
 
MultipleChoiceField(ChoiceField)
    ...
 
TypedMultipleChoiceField(MultipleChoiceField)
    coerce = lambda val: val   对选中的每一个值进行一次转换
    empty_value= ''            空值的默认值
 
ComboField(Field)
    fields=()                  使用多个验证,如下:即验证最大长度20,又验证邮箱格式
                               fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])
 
MultiValueField(Field)         *被继承
    PS: 抽象类,子类中可以实现聚合多个字典去匹配一个值,要配合MultiWidget使用
 
SplitDateTimeField(MultiValueField)    *一下生成三个输入框
    input_date_formats=None,   格式列表:['%Y--%m--%d', '%m%d/%Y', '%m/%d/%y']
    input_time_formats=None    格式列表:['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
 
FilePathField(ChoiceField)     *文件选项,目录下文件显示在页面中 提交时是文件路径
    path,                      文件夹路径
    match=None,                正则匹配
    recursive=False,           递归下面的文件夹
    allow_files=True,          允许文件
    allow_folders=False,       允许文件夹
    required=True,
    widget=None,
    label=None,
    initial=None,
    help_text=''
 
GenericIPAddressField
    protocol='both',           both,ipv4,ipv6支持的IP格式
    unpack_ipv4=False          解析ipv4地址,如果是::ffff:192.0.2.1时候,可解析为192.0.2.1, PS:protocol必须为both才能启用
 
SlugField(CharField)           数字,字母,下划线,减号(连字符)
    ...
 
UUIDField(CharField)           uuid类型
    ...

Django内置字段
Django内置字段

2、内置插件

* 插件用于生成HTML,所有的插件都可以用attrs={'class':'c1'}创建默认值

TextInput(Input)
NumberInput(TextInput)
EmailInput(TextInput)
URLInput(TextInput)
PasswordInput(TextInput)
HiddenInput(TextInput)
Textarea(Widget)
DateInput(DateTimeBaseInput)
DateTimeInput(DateTimeBaseInput)
TimeInput(DateTimeBaseInput)
CheckboxInput
Select
NullBooleanSelect
SelectMultiple
RadioSelect
CheckboxSelectMultiple
FileInput
ClearableFileInput
MultipleHiddenInput
SplitDateTimeWidget
SplitHiddenDateTimeWidget
SelectDateWidget
Django内置插件

3、表单验证

处理文件:

from django import forms
class Verification(forms.Form):
    # 跟表单提交的name值一一对应进行验证
    user = forms.CharField(error_messages={'required':'用户名不能为空'})
    pwd = forms.CharField(
        max_length=12,
        min_length=6,
        error_messages={'required': '密码不能为空','min_length':'密码长度不能小于6位',
                        'max_length': '密码长度不能大于12位'}
    )
    email = forms.EmailField(error_messages={'required':'用户名不能为空','invalid':'邮箱格式不正确'})

def login(request):
    if request.method == "GET":
        obj = Verification()
        return render(request,'login.html',{'obj':obj})
    elif request.method == "POST":
        # 获取用户所有数据
        # 每条数据请求的验证
        # 成功:获取所有的正确的信息
        # 失败:显示错误信息
        obj = Verification(request.POST)
        result = obj.is_valid()         # 进行验证 True/False
        if result:
            print(obj.cleaned_data)     # 用户提交的正确信息
        else:
            print(obj.errors.as_json)       # 所有错误信息 obj.errors
            return render(request, 'login.html',{'obj':obj})    # 传入obj

        return redirect('/login/')

HTML文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/login/" method="post">
        {% csrf_token  %}
        <p>用户:{{ obj.user }}{{ obj.errors.user.0 }}</p>
        <p>密码:{{ obj.pwd }}{{ obj.errors.pwd.0 }}</p>
        <p>邮箱:{{ obj.email }}{{ obj.errors.email.0 }}</p>
        <input type="submit" name="提交" />
    </form>
</body>
</html>
login.html

其他标签使用:

<form method="POST" enctype="multipart/form-data">
        {% csrf_token %}
        
            {{ form.xxoo.label }}
            {{ form.xxoo.id_for_label }}
            {{ form.xxoo.label_tag }}
            {{ form.xxoo.errors }}
            <p>{{ form.user }} {{ form.user.errors }}</p>
            <input type="submit" />
    </form>

其他标签有
其他标签使用

补充:cleaned_data(字典格式)创建和更新

models.UserInfo.objects.create(**obj.cleaned_data)
models.UserInfo.objects.filter(id=1).update(**obj.cleaned_data)

  

4、更多验证方式:

验证文件:

from django import forms
from django.forms import widgets
from django.forms import fields
class Verification(forms.Form):
    # 跟表单提交的name值一一对应进行验证
    user = fields.CharField(
        widget=widgets.Textarea(attrs={'class':'c1'}),      # 定制样式,变成长框输入,添加样式class=c1
        label="用户名:"           # 左边显示信息
    )
    pwd = fields.CharField(
        max_length=12,
        min_length=6,
        widget=widgets.PasswordInput()      # 定制密码格式
    )
    f = fields.FileField()      # 上传文件
    p = fields.FilePathField(path='app01')      # 显示路径 提交数据为路径值
    email = fields.EmailField()
    city1 = fields.ChoiceField(         # 单选下拉框
        choices=[(0, '上海'), (1, '广州'), (2, '东莞')]
    )
    city2 = fields.MultipleChoiceField(     # 多选下拉框
        choices=[(0, '上海'), (1, '广州'), (2, '东莞')]
    )

HTML文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/login/" method="post">
        {% csrf_token  %}
        <p>{{ obj.user }}{{ obj.errors.user.0 }}</p>
        <p>{{ obj.pwd }}{{ obj.errors.pwd.0 }}</p>
        <p>{{ obj.email }}{{ obj.errors.email.0 }}</p>
        <p>{{ obj.f }}{{ obj.errors.f.0 }}</p>
        <p>{{ obj.p }}</p>
        <p>{{ obj.city1 }}</p>
        <p>{{ obj.city2 }}</p>
        <input type="submit" name="提交" />
    </form>
</body>
</html>
login.html

 

5、常用选择插件

# 单radio,值为字符串
user = fields.CharField(
    initial=2,
    widget=widgets.RadioSelect(choices=((1,'上海'),(2,'北京'),))
)

# 单radio,值为字符串
user = fields.ChoiceField(
    choices=((1, '上海'), (2, '北京'),),
    initial=2,
    widget=widgets.RadioSelect
)

# 单select,值为字符串
user = fields.CharField(
    initial=2,
    widget=widgets.Select(choices=((1,'上海'),(2,'北京'),))
)

# 单select,值为字符串
user = fields.ChoiceField(
    choices=((1, '上海'), (2, '北京'),),
    initial=2,
    widget=widgets.Select
)

# 多选select,值为列表
user = fields.MultipleChoiceField(
    choices=((1,'上海'),(2,'北京'),),
    initial=[1,],
    widget=widgets.SelectMultiple
)


# 单checkbox
user = fields.CharField(
    widget=widgets.CheckboxInput()
)


# 多选checkbox,值为列表
user = fields.MultipleChoiceField(
    initial=[2, ],
    choices=((1, '上海'), (2, '北京'),),
    widget=widgets.CheckboxSelectMultiple
Django选择插件

 

6、初始默认显示数据

在Web应用程序中开发编写功能时,时常用到获取数据库中的数据并将值初始化在HTML中的标签上

验证文件:

from django import forms
from django.forms import widgets
from django.forms import fields
class Verification(forms.Form):
    # 跟表单提交的name值一一对应进行验证
    user = fields.CharField(
        widget=widgets.Textarea(attrs={'class':'c1'}),      # 定制样式,变成长框输入,添加样式class=c1
        label="用户名:"           # 左边显示信息
    )
    pwd = fields.CharField(
        max_length=12,
        min_length=6,
        widget=widgets.PasswordInput()      # 定制密码格式
    )
    # f = fields.FileField()      # 上传文件
    p = fields.FilePathField(path='app01')      # 显示路径 提交数据为路径值
    email = fields.EmailField()
    city1 = fields.ChoiceField(         # 单选下拉框
        choices=[(0, '上海'), (1, '广州'), (2, '东莞')]
    )
    city2 = fields.MultipleChoiceField(     # 多选下拉框
        choices=[(0, '上海'), (1, '广州'), (2, '东莞')]
    )
创建验证类

处理文件:

def login(request):
    if request.method == "GET":
        # 从数据库中吧数据获取到
        dic = {
            "user": 'r1',
            'pwd': '123123',
            'email': 'sdfsd',
            'city1': 1,
            'city2': [1, 2]
        }
        # obj = Verification({'user':'James','pwd':'123123'})   # 设置初始默认显示
        obj = Verification(initial=dic)       # 设置初始默认显示
        return render(request, 'login.html', {'obj': obj})
    elif request.method == "POST":
        obj = Verification(request.POST)
        result = obj.is_valid()         # 进行验证 True/False
        if result:
            print(obj.cleaned_data)     # 用户提交的正确信息
        else:
            print(obj.errors.as_json)       # 所有错误信息 obj.errors
            return render(request, 'login.html',{'obj':obj})    # 传入obj

        return redirect('/login/')

HTML文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/login/" method="post">
        {% csrf_token  %}
        <p>{{ obj.user }}{{ obj.errors.user.0 }}</p>
        <p>{{ obj.pwd }}{{ obj.errors.pwd.0 }}</p>
        <p>{{ obj.email }}{{ obj.errors.email.0 }}</p>
{#        <p>{{ obj.f }}{{ obj.errors.f.0 }}</p>#}
        <p>{{ obj.p }}</p>
        <p>{{ obj.city1 }}</p>
        <p>{{ obj.city2 }}</p>
        <input type="submit" name="提交" />
    </form>
</body>
</html>
login.html 

 

7、Form操作动态Select数据

其他文件:

from django.db import models

class UserType(models.Model):
    name = models.CharField(max_length=32)

class User(models.Model):
    user = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)
    ut = models.ForeignKey(to='UserType',
                           to_field='id',
                           related_name='b',
                           related_query_name='a',
                           limit_choices_to={'id__gt':1})
models.py
from app01.forms import UserInfoForm
def index(request):

    obj = UserInfoForm()

    return render(request,'index.html',{'obj':obj})
views.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>{{ obj.user }}</p>
    <p>{{ obj.pwd }}</p>
    <p>{{ obj.user_type }}</p>
</body>
</html>
index.html

在app下创建forms.py文件做验证:

from django import forms
from django.forms import fields
from django.forms import widgets
from app01 import models

class UserInfoForm(forms.Form):
    user = fields.CharField(
        required=False,
        widget = widgets.Textarea(attrs={'class':'c1'})
    )
    pwd = fields.CharField(
        max_length=12,
        widget = widgets.PasswordInput(attrs={'class':'c1'})
    )
    user_type = fields.ChoiceField(
        # choices=[(1,'普通用户'),(2,'超级用户'),],
        choices=models.UserType.objects.values_list('id','name'),
        widget = widgets.Select
    )

执行Django程序,访问页面,可以获得动态的select选择框;但是会遇到问题,当UserType增加数据后,页面select选择框的内容并没有做改变,除非重启Django程序;这里涉及到实例变量和类变量,当实例化的时候,需要对类变量(静态字段)user_type进行重构

 对forms.py进行修改:

from django import forms
from django.forms import fields
from django.forms import widgets
from app01 import models

class UserInfoForm(forms.Form):
    user = fields.CharField(
        required=False,
        widget = widgets.Textarea(attrs={'class':'c1'})
    )
    pwd = fields.CharField(
        max_length=12,
        widget = widgets.PasswordInput(attrs={'class':'c1'})
    )
    user_type = fields.ChoiceField(
        choices=[],
        widget = widgets.Select
    )
    user_type2 = fields.CharField(
        widget=widgets.Select(choices=[],),
    )
    #
    def __init__(self,*args,**kwargs):
        super(UserInfoForm,self).__init__(*args,**kwargs)   # 执行父类重构
        self.fields['user_type'].choices = models.UserType.objects.values_list('id', 'name')
        self.fields['user_type2'].widget.choices = models.UserType.objects.values_list('id', 'name')

 

8、添加自定义验证,重构钩子 

Form数据验证顺序:

  • 先正则检查字段
  • 然后执行_clean_%s 检查各个字段
  • 执行_clean_form
  • 最后执_post_clean

对于错误信息:

  • obj.errors里面有一个“__all__”来存放整体错误信息
  • 单个字段存放单个的错误信息

  寻找钩子

Form通过obj.is_valid()进行表单验证,通过self.errors查到forms.py文件的full_clean()

def full_clean(self):
     ......
        self._clean_fields()
        self._clean_form()
        self._post_clean()
def full_clean(self):

        self._clean_fields()
        self._clean_form()
        self._post_clean()

def _clean_fields(self):            #单个字段钩子
            try:
                if isinstance(field, FileField):
                    initial = self.initial.get(name, field.initial)
                    value = field.clean(value, initial)
                else:
                    value = field.clean(value)
                self.cleaned_data[name] = value
                if hasattr(self, 'clean_%s' % name):
                    value = getattr(self, 'clean_%s' % name)()
                    self.cleaned_data[name] = value
            except ValidationError as e:
                self.add_error(name, e)

def _clean_form(self):        #整体钩子
        try:
            cleaned_data = self.clean()
        except ValidationError as e:
            self.add_error(None, e)
        else:
            if cleaned_data is not None:
                self.cleaned_data = cleaned_data

def _post_clean(self):
        """
        An internal hook for performing additional cleaning after form cleaning
        is complete. Used for model validation in model forms.
        """
        pass
钩子...

  注册用户,自定义验证已存在用户不能注册

class RegisterForm(forms.Form):
    user = fields.CharField()
    email = fields.EmailField()

    def clean_user(self):       #验证用户是否已经存在
        c = models.UserInfo.objects.filter(name=self.cleaned_data["user"])
        if not c:
            return self.cleaned_data["user"]
        else:                  #用户名已存在,触发错误,提示用户名存在
            raise ValidationError(message="用户名已经存在", code="a001")

    def clean_email(self):
        return self.cleaned_data["email"]

  用户登录验证,自定义整体错误,用户名或密码错误

from django.core.exceptions import ValidationError

class RegisterForm(forms.Form):
    user = fields.CharField()
    email = fields.EmailField()

    def clean(self):            #整体错误输出
        #判断是否存在
        c = models.UserInfo.objects.filter(name=self.cleaned_data['user'],pwd=self.cleaned_data['pwd'])
        if c :
            return self.cleaned_data    #返回正常值
        else:
            raise ValidationError(message='用户名或密码错误')   #触发错误,错误发给整体而非某个字段

如果错误可以通过obj.errors获取错误的信但是通过_clean_form验证整体的错误信息在obj.errors里面有一个“__all__”来存放整体错误信息

打印整体错误信息:

from app01.forms import RegisterForm
def login(request):
    if request.method == "GET":
        obj = RegisterForm()
        return render(request, 'login.html', {'obj': obj})
    elif request.method == "POST":
        obj = RegisterForm(request.POST)
        result = obj.is_valid()         
        if result:
            print(obj.cleaned_data)     
        else:
            print(obj.errors['__all__'])   #整体的错误信息打印
            return render(request, 'login.html',{'obj':obj})    # 传入obj
from app01.forms import RegisterForm
from django.core.exceptions import NON_FIELD_ERRORS
def login(request):
    if request.method == "GET":
        obj = RegisterForm()
        return render(request, 'login.html', {'obj': obj})
    elif request.method == "POST":
        obj = RegisterForm(request.POST)
        result = obj.is_valid()
        if result:
            print(obj.cleaned_data)
        else:
            print(obj.errors[NON_FIELD_ERRORS])   #整体的错误信息打印
            return render(request, 'login.html',{'obj':obj})    # 传入obj
另一种方式,NON_FIELD_ERRORS

  _post_clean还可自定制这个方法

  

9、Ajax提交验证(序列化)  

关于Django中的序列化主要应用在将数据库中检索的数据返回给客户端用户,特别的Ajax请求一般返回的为Json格式;之前表单用form提交数据验证没有什么问题,现在我们要做在Ajax的情况下,如何去做:

其他文件:

<!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>
        <p><input type="button" id="btn" value="Ajax提交"></p>
    </form>
    <script src="/static/jquery-1.12.4.js"></script>
    <script>
        $(function () {
            $('#btn').click(function () {
                $.ajax({
                    url:'/login/',
                    type:'POST',
                    data:$('#fm').serialize(),
                    success:function (arg) {
                        console.log(arg)
                        arg = JSON.parse(arg)
                        console.log(arg)
                        console.log(arg['error']['username'][0])
                    },error:function () {

                    }
                })

            })
        })
    </script>
</body>
</html>
login.html
from django import forms
from django.forms import fields
from django.forms import widgets
from app01 import models

class LoginForm(forms.Form):

    username = fields.CharField()
    password = fields.CharField(
        max_length=20,
        min_length=12,
    )
forms.py

处理文件:

import json
from app01.forms import LoginForm
def login(request):
    if request.method == "GET":
        return render(request, 'login.html')
    elif request.method == "POST":
        data = {'status':True,'error':None,'data':None}
        obj = LoginForm(request.POST)
        result = obj.is_valid()
        if result:
            print(obj.cleaned_data)
        else:
            from django.forms.utils import  ErrorDict
            print(type(obj.errors))   #整体的错误信息打印
            # < class 'django.forms.utils.ErrorDict'>
            data['error'] = obj.errors

    return HttpResponse(json.dumps(data))    # 传入obj

EroorDict信息:

@html_safe
@python_2_unicode_compatible
class ErrorDict(dict):
    """
    A collection of errors that knows how to display itself in various formats.

    The dictionary keys are the field names, and the values are the errors.
    """
    def as_data(self):
        return {f: e.as_data() for f, e in self.items()}

    def as_json(self, escape_html=False):
        return json.dumps({f: e.get_json_data(escape_html) for f, e in self.items()})

    def as_ul(self):
        if not self:
            return ''
        return format_html(
            '<ul class="errorlist">{}</ul>',
            format_html_join('', '<li>{}{}</li>', ((k, force_text(v)) for k, v in self.items()))
        )

    def as_text(self):
        output = []
        for field, errors in self.items():
            output.append('* %s' % field)
            output.append('\n'.join('  * %s' % e for e in errors))
        return '\n'.join(output)

    def __str__(self):
        return self.as_ul()
ErrorDict

武sir说课上说 ErrorDict不是Dict的格式,无法用json.dumps进行序列化,所以上面代码是错误的;但是,我个人测试的结果是可以打印出错误信息的,这点暂时存疑

浏览器:
{"data": null, "status": true, "error": {"password": ["This field is required."], 
"username": ["This field is required."]}}
Object {data: null, status: true, error: Object}data: nullerror: Objectstatus: true__proto__: Object
 This field is required.

用as_json()把ErrorDict转换为字符串然后传入data字典

处理文件:

import json
from app01.forms import LoginForm
def login(request):
    ---snip---
        else:
            print(type(obj.errors.as_json()))   #整体的错误信息打印
            # <class 'str'>
            data['error'] = obj.errors.as_json()    #把ErrorDict格式的obj.error转换为字符串格式

    return HttpResponse(json.dumps(data))    # 传入

浏览器打印:

{"status": true, "data": null, "error": "{\"username\": [{\"code\": \"required\", \"message\": \"This field is required.\"}], \"password\": [{\"code\": \"required\", \"message\": \"This field is required.\"}]}"}
Object {status: true, data: null, error: "{"username": [{"code": "required", "message": "Thi…equired", "message": "This field is required."}]}"}
   data: null
   error: "{"username": [{"code": "required", "message": "This field is required."}], "password": [{"code": "required", "message": "This field is required."}]}"
   status: true

从上面可看到error打印出来的格式还是字符串,由于之前用as_json进行过一次序列化,json.dumps后又进行一次序列化;进行了两次序列化,所以反序列化时也需要两次

用as_data()通过自定制json方法进行序列化

处理文件:

import json
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)

from app01.forms import LoginForm
def login(request):
    ---snip---
        else:
            print(type(obj.errors.as_data()))   #as_data虽然变成了字典,但是也不能直接dump
            # <class 'dict'>
            print(obj.errors.as_data())         #里面包含了ValidationError类型序列化会报错
            # 'password': [ValidationError(['This field is required.'])], 'username': [
            #     ValidationError(['This field is required.'])]}
            data['error'] = obj.errors.as_data()
            data = json.dumps(data, cls=JsonCustomEncoder)   #自定义JsonCustomEncoder方法序列化

    return HttpResponse(json.dumps(data))    # 传入

补充:由于json.dumps时无法处理datetime日期,所以可以通过自定义处理器来做扩展,如:

import json
from datetime import date
from datetime import datetime

class JsonCustomEncoder(json.JSONEncoder):
    def default(self, field):

        if isinstance(field, datetime):
            return field.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(field, date):
            return field.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, field)
v = {'k':123,'k1':datetime.now()}
ds = json.dumps(v, cls=JsonCustomEncoder)
json自定制序列化方法

 

serializers对QuerySet类型数据序列化

from app01 import models
from django.core import serializers
def index(request):
    v = models.User.objects.all()       #QuerySet类型
    # print(v)
    # <QuerySet[{'pwd': '123', 'user': 'root'}]>
    # json.dumps(v)                 #直接dumps会报错
    data = serializers.serialize("json", v)     #serializers方法
    print(type(data))
    # [{"model": "app01.user", "pk": 1, "fields": {"user": "root", "pwd": "123"}},]
    # < class 'str'>                    #类型
    return HttpResponse('OK')

QuerySet类型列表、字典序列化

from app01 import models
def index(request):
    v = models.User.objects.values_list('user','pwd')       #QuerySet类型
    print(v)
    # < QuerySet[('root', '123')] >
    # json.dumps(v)                 #直接dumps会报错
    data = list(v)
    json.dumps(data)

    return HttpResponse('OK')

如果values()取出来的值包含时间类型或其他,则依然不能进行dumps,需要跟之前自定制序列化方法结合起来使用

 

更多-》跳转 


《第二十二章》

  

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!