Django之Form初识

Django之Form基本功能

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

基本使用

创建Form类

from django.forms import Form
from django.forms import widgets
from django.forms import fields
 
class MyForm(Form):
    user = fields.CharField(
        required=True,
        min_length=6,error_messages={"required": '用户名不能为空','min_length': '用户名长度不能小6'}
        widget=widgets.TextInput(attrs={'id': 'i1', 'class': 'c1'})
    )
 
    gender = fields.ChoiceField(
        choices=((1, '男'), (2, '女'),),
        initial=2,
        widget=widgets.RadioSelect
    )
 
    city = fields.CharField(
        initial=2,
        widget=widgets.Select(choices=((1,'上海'),(2,'北京'),))
    )
 
    pwd = fields.CharField(
        widget=widgets.PasswordInput(attrs={'class': 'c1'}, render_value=True)
    )

Form有一些定义好正则表达式的字段,这些字段都有对应的code和message,可以借助error_messages进行重写,error_messages优先级更高

views函数

from django.shortcuts import render, redirect
from .forms import MyForm
 
 
def index(request):
    if request.method == "GET":
        obj = MyForm({'user', 'jack', pwd='123456'})
        return render(request, 'index.html', {'form': obj})
    elif request.method == "POST":
        obj = MyForm(request.POST, request.FILES)
        if obj.is_valid():
            values = obj.cleaned_data
            print(values)
        else:
            errors = obj.errors
            print(errors)
        return render(request, 'index.html', {'form': obj})
    else:
        return redirect('http://www.google.com')

ajax提交的views

def login_ajax(request):
    if request.method == "GET":
        return render(request, 'login_ajax.html')
    elif request.method == "POST":
        ret = {'status': True, 'error':None, 'data': None}
        obj = LoginForm(request.POST)
        if obj.is_valid():
            print(obj.clean())
        else:
            # 方式一
            # res_str = obj.errors.as_json() # res_str是一个字符串
            # ret['status'] = False
            # ret['error'] = res_str
            # 两次反序列化
            # 方式二:
            ret['status'] = False
            # obj.errors.users 是一个ErrorList 类型,  obj.errors.users[0] 才是真真的字符串类型
            ret['error'] = obj.errors.as_data() # # {'user': [ValidationError(['用户名长度不能小6'])], 'email': [ValidationError(['邮箱格式错误'])]}
            # # 一次反序列化
        return HttpResponse(json.dumps(ret,cls=JsonCustomEncoder))

from django.core.validators import ValidationError
class JsonCustomEncoder(json.JSONEncoder):
    def default(self, field):
        if isinstance(field, ValidationError):
            return {'code': field.code, 'message': field.message}
        else:
            return json.JSONEncoder.default(self, field)

上述是旧版本,其实不用借助as_data() 也能完成,因为obj.errors继承于字典,所以也可以json.dumps,此时需要把tag.innerHTML = v[0].message;改成tag.innerHTML = v[0];

前端模板

<form action="/" method="POST" enctype="multipart/form-data">
    {% for column in form %}
        <p>{{ column }} {{  column.errors.0 }}</p>
    {% endfor %}

    <input type="submit"/>
</form>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .error-msg{
            color: red;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <h1>Form提交数据</h1>
    <form id="f1">
    <p>
        <input id="u" type="text" name="user" placeholder="用户名" />

    </p>
    <p>
        <input id="e" type="text" name="email" placeholder="邮箱" />
    </p>
    <p>
        <input id="p" type="text" name="pwd" placeholder="密码" />
    </p>
    <input id="ajax_submit" type="button" value="Ajax提交"  />
        </form>
    <script src="/static/jquery-2.1.4.min.js"></script>
    <script>
        $(function () {
            $('#ajax_submit').click(function () {
                $.ajax({
                    url:"/login_ajax.html",
                    //data: {user: $('#u').val(), email: $('#e').val(), pwd: $('#p').val()},
                    data: $('#f1').serialize(),
                    type: 'POST',
                    success:function (arg) {
                        $('.error-msg').remove();
                        var v1 = JSON.parse(arg);
                        if(!v1.status){
                            // var error_obj = JSON.parse(v1.error);
                            var error_obj = v1.error;
                            $.each(error_obj,function (k,v) {
                                // k: user 或 email
                                // v: [{}{}{},]
                                var tag = document.createElement('span');
                                tag.className = 'error-msg';
                                tag.innerHTML = v[0].message;
                                $("input[name='" + k +"']").after(tag);
                            })
                        }else{
                            location.href = "/inde.html"
                        }
                        // { 'stauts': true, 'error':xx, 'data':’‘}
                    }
                })
            })
        })
    </script>
</body>
</html>
posted @ 2018-06-06 21:42  龙云飞谷  阅读(134)  评论(0编辑  收藏  举报