Python进阶32-Django forms组件

2022-09-26 12:41:51 浏览数 (1)

  • forms组件功能介绍
  • 项目案例
  • 结合前端传递数据校验
  • 渲染模板功能
  • 渲染错误信息
  • 局部钩子
  • 全局钩子
  • 实现注册功能

-曾老湿, 江湖人称曾老大。


-多年互联网运维工作经验,曾负责过大规模集群架构自动化运维管理工作。 -擅长Web集群架构与自动化运维,曾负责国内某大型金融公司运维工作。 -devops项目经理兼DBA。 -开发过一套自动化运维平台(功能如下): 1)整合了各个公有云API,自主创建云主机。 2)ELK自动化收集日志功能。 3)Saltstack自动化运维统一配置管理工具。 4)Git、Jenkins自动化代码上线及自动化测试平台。 5)堡垒机,连接Linux、Windows平台及日志审计。 6)SQL执行及审批流程。 7)慢查询日志分析web界面。


forms组件功能介绍


forms组件介绍

基本上就是一个类,可以校验前台传过来的字段

1.校验字段功能 2.渲染标签功能 3.渲染错误信息功能

例如写一个注册页面,如果页面中只需要输入用户名和密码,那就写一写if判断就好,但是如果有一堆注册信息要填写呢?

难道要写一万个判断嘛?会死人的,所以Django提供了forms组件,专门根据规则校验字段

项目案例


创建项目

代码语言:javascript复制
### 路由 
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index_form/', views.index_form),
]
代码语言:javascript复制
### 失败的校验

from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse

# Create your views here.

## forms组件数据校验功能
# 0.导入模块
from django import forms
# 1.是个类,先要继承Form
class MyForm(forms.Form):
# 2.定义一个属性可以校验字符串类型
    # 限制字符串,最大长度是8最小长度是3
    name=forms.CharField(max_length=8,min_length=3)
    pwd=forms.CharField(max_length=8,min_length=3)
    # 校验邮箱格式
    email=forms.EmailField()


def index_form(request):
    # 生成对象,需要传入要校验的对象(数据是字典)
    dic = {'name':'zls','pwd':'123','email':'33'}
    myform = MyForm(dic)
    # is_vallid 方法 ,如果返回True则校验成功,反之则校验失败
    if myform.is_valid():
        return HttpResponse('校验成功')
    else:
        return HttpResponse('校验失败')

代码语言:javascript复制
### 成功的校验

from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse

# Create your views here.

## forms组件数据校验功能
# 0.导入模块
from django import forms
# 1.是个类,先要继承Form
class MyForm(forms.Form):
# 2.定义一个属性可以校验字符串类型
    # 限制字符串,最大长度是8最小长度是3
    name=forms.CharField(max_length=8,min_length=3)
    pwd=forms.CharField(max_length=8,min_length=3)
    # 校验邮箱格式
    email=forms.EmailField()


def index_form(request):
    # 生成对象,需要传入要校验的对象(数据是字典)
    dic = {'name':'zls','pwd':'123','email':'33@qq.com'}
    myform = MyForm(dic)
    # is_vallid 方法 ,如果返回True则校验成功,反之则校验失败
    if myform.is_valid():
        return HttpResponse('校验成功')
    else:
        return HttpResponse('校验失败')

代码语言:javascript复制
### 打印校验通过的数据

from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse

# Create your views here.

## forms组件数据校验功能
# 0.导入模块
from django import forms
# 1.是个类,先要继承Form
class MyForm(forms.Form):
# 2.定义一个属性可以校验字符串类型
    # 限制字符串,最大长度是8最小长度是3
    name=forms.CharField(max_length=8,min_length=3)
    pwd=forms.CharField(max_length=8,min_length=3)
    # 校验邮箱格式
    email=forms.EmailField()


def index_form(request):
    # 生成对象,需要传入要校验的对象(数据是字典)
    dic = {'name':'zls','pwd':'123','email':'33@qq.com'}
    myform = MyForm(dic)
    # is_vallid 方法 ,如果返回True则校验成功,反之则校验失败
    if myform.is_valid():
        # 打印校验通过的数据
        print(myform.cleaned_data)
        return HttpResponse('校验成功')
    else:
        return HttpResponse('校验失败')

代码语言:javascript复制
### 打印错误信息
from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse

# Create your views here.

## forms组件数据校验功能
# 0.导入模块
from django import forms
# 1.是个类,先要继承Form
class MyForm(forms.Form):
# 2.定义一个属性可以校验字符串类型
    # 限制字符串,最大长度是8最小长度是3
    name=forms.CharField(max_length=8,min_length=3)
    pwd=forms.CharField(max_length=8,min_length=3)
    # 校验邮箱格式
    email=forms.EmailField()


def index_form(request):
    # 生成对象,需要传入要校验的对象(数据是字典)
    dic = {'name':'zls','pwd':'12','email':'33@qq.com'}
    myform = MyForm(dic)
    # is_vallid 方法 ,如果返回True则校验成功,反之则校验失败
    if myform.is_valid():
        # 打印校验通过的数据
        print(myform.cleaned_data)
        return HttpResponse('校验成功')
    else:
        print(myform.errors)
        return HttpResponse('校验失败')

结合前端传递数据校验


后端代码

代码语言:javascript复制
from django.shortcuts import render,HttpResponse,redirect
from django.http import JsonResponse

# Create your views here.

## forms组件数据校验功能
# 0.导入模块
from django import forms
# 1.是个类,先要继承Form
class MyForm(forms.Form):
# 2.定义一个属性可以校验字符串类型
    # 限制字符串,最大长度是8最小长度是3
    name=forms.CharField(max_length=8,min_length=3)
    pwd=forms.CharField(max_length=8,min_length=3)
    # 校验邮箱格式
    email=forms.EmailField()


def index_form(request):
    if request.method == 'GET':
        return render(request,'index_form.html')
    elif request.method == 'POST':
        print(request.POST)
        # 生成对象,需要传入要校验的对象(数据是字典)
        myform = MyForm(request.POST)
        # is_vallid 方法 ,如果返回True则校验成功,反之则校验失败
        if myform.is_valid():
            # 打印校验通过的数据
            print(myform.cleaned_data)
            return HttpResponse('校验成功')
        else:
            print(myform.errors)
            return HttpResponse('校验失败')

前端代码

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>forms组件</title>
</head>
<body>
<form action="" method="post">
    <lable>用户:<input type="text" name="name"></lable>
    <lable>密码:<input type="text" name="pwd"></lable>
    <lable>邮箱:<input type="text" name="email"></lable>
    <input type="submit" value="提交">
</form>
</body>
</html>

渲染模板功能


添加路由

代码语言:javascript复制
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index_form/', views.index_form),
    url(r'^index2/', views.index2),
]

添加视图

代码语言:javascript复制
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse

# Create your views here.

## forms组件数据校验功能
# 0.导入模块
from django import forms


# 1.是个类,先要继承Form
class MyForm(forms.Form):
    # 2.定义一个属性可以校验字符串类型
    # 限制字符串,最大长度是8最小长度是3
    name = forms.CharField(max_length=8, min_length=3)
    pwd = forms.CharField(max_length=8, min_length=3)
    # 校验邮箱格式
    email = forms.EmailField()

def index2(request):
    myform = MyForm()
    if request.method == 'GET':
        return render(request,'index2.html',locals())

渲染模板:方法一

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="" method="post">
    <lable>用户:{{ myform.name }}</lable>
    <lable>密码:{{ myform.pwd }}</lable>
    <lable>邮箱:{{ myform.email }}</lable>
    <input type="submit" value="提交">
</form>
</body>
</html>

神奇的事情发生了,我们删除了input框,结果页面上还有,并且...还在input框里添加了字段的限制规则,并且直接点提交,还能提示我,我擦嘞~~~格式错了,还能报错 ,这就很舒服


渲染模板:方法二

第二种方式特别牛逼,直接for循环 forms对象

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>渲染模板方法一:</h1>
    <form action="" method="post">
    <lable>用户:{{ myform.name }}</lable>
    <lable>密码:{{ myform.pwd }}</lable>
    <lable>邮箱:{{ myform.email }}</lable>
    <input type="submit" value="提交">
</form>
<hr>
<h1>渲染模板方法二:</h1>
{% for foo in myform %}
    {{ foo }}
{% endfor %}
<input type="submit" value="提交">
</body>
</html>

好像没有字...

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>渲染模板方法二:</h1>
<form action="" method="post">
    {% for foo in myform %}
        {{ foo.label }}:{{ foo }}
    {% endfor %}
    <input type="submit" value="提交">
</form>
</body>
</html>

想显示中文?简单

代码语言:javascript复制
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse

# Create your views here.

## forms组件数据校验功能
# 0.导入模块
from django import forms


# 1.是个类,先要继承Form
class MyForm(forms.Form):
    # 2.定义一个属性可以校验字符串类型
    # 限制字符串,最大长度是8最小长度是3
    name = forms.CharField(max_length=8, min_length=3,label='用户')
    pwd = forms.CharField(max_length=8, min_length=3,label='密码')
    # 校验邮箱格式
    email = forms.EmailField(label='邮箱')

def index2(request):
    myform = MyForm()
    if request.method == 'GET':
        return render(request,'index2.html',locals())


渲染模板:方法三

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>渲染模板方法三:</h1>
<form action="" method="post">
    {{ myform.as_ul }}
    <input type="submit" value="提交">
</form>
</body>
</html>

第三种方法,不建议使用,没有办法加样式。

渲染错误信息


创建路由

代码语言:javascript复制
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index_form/', views.index_form),
    url(r'^index2/', views.index2),
    url(r'^index3/', views.index3),
]

添加视图

代码语言:javascript复制
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse

# Create your views here.

## forms组件数据校验功能
# 0.导入模块
from django import forms


# 1.是个类,先要继承Form
class MyForm(forms.Form):
    # 2.定义一个属性可以校验字符串类型
    # 限制字符串,最大长度是8最小长度是3
    name = forms.CharField(max_length=8, min_length=3,label='用户')
    pwd = forms.CharField(max_length=8, min_length=3,label='密码')
    # 校验邮箱格式
    email = forms.EmailField(label='邮箱')

def index3(request):
    if request.method == 'GET':
        myform = MyForm()
    elif request.method == 'POST':
        myform = MyForm(request.POST)
    return render(request, 'index3.html', locals())

前端代码

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>渲染错误信息</title>
</head>
<body>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>使用渲染模板的第二种方式渲染错误信息:</h1>
<form action="" method="post" novalidate>
    {% for foo in myform %}
        <div>{{ foo.label }}:{{ foo }} <span>{{ foo.errors.0 }}</span></div>
    {% endfor %}
    <input type="submit" value="提交">
</form>
</body>
</html>


换成中文

代码语言:javascript复制
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse

# Create your views here.

## forms组件数据校验功能
# 0.导入模块
from django import forms


# 1.是个类,先要继承Form
class MyForm(forms.Form):
    # 2.定义一个属性可以校验字符串类型
    # 限制字符串,最大长度是8最小长度是3
    name = forms.CharField(max_length=8, min_length=3, label='用户',
                           error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'})
    pwd = forms.CharField(max_length=8, min_length=3, label='密码',
                          error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'})
    # 校验邮箱格式
    email = forms.EmailField(label='邮箱', required=True, error_messages={'invalid':'必须是邮箱格式啊~我的哥'})


密码密文

密码是明文的,需要修改一下样式。

使用widgets,可以导入,也可以直接使用from django.forms import widgets

代码语言:javascript复制
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse

# Create your views here.

## forms组件数据校验功能
# 0.导入模块
from django import forms


# 1.是个类,先要继承Form
class MyForm(forms.Form):
    # 2.定义一个属性可以校验字符串类型
    # 限制字符串,最大长度是8最小长度是3
    name = forms.CharField(max_length=8, min_length=3, label='用户',
                           error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'},
                           widget=forms.widgets.TextInput())
    pwd = forms.CharField(max_length=8, min_length=3, label='密码',
                          error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'},
                          widget=forms.widgets.PasswordInput())
    # 校验邮箱格式
    email = forms.EmailField(label='邮箱', required=True, error_messages={'invalid': '必须是邮箱格式啊~我的哥'},
                             widget=forms.widgets.EmailInput())


def index3(request):
    if request.method == 'GET':
        myform = MyForm()
    elif request.method == 'POST':
        myform = MyForm(request.POST)
    return render(request, 'index3.html', locals())


指定input框的样式

首先引用bootstrap,或者自己写css

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>渲染错误信息</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

</head>
<body>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>使用渲染模板的第二种方式渲染错误信息:</h1>
<form action="" method="post" novalidate>
    {% for foo in myform %}
        <div>{{ foo.label }}:{{ foo }} <span>{{ foo.errors.0 }}</span></div>
    {% endfor %}
    <input type="submit" value="提交">
</form>
</body>
</html>

修改forms类

代码语言:javascript复制
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse

# Create your views here.

## forms组件数据校验功能
# 0.导入模块
from django import forms


# 1.是个类,先要继承Form
class MyForm(forms.Form):
    # 2.定义一个属性可以校验字符串类型
    # 限制字符串,最大长度是8最小长度是3
    name = forms.CharField(max_length=8, min_length=3, label='用户',
                           error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'},
                           widget=forms.widgets.TextInput(attrs={'class':'form-control'}))
    pwd = forms.CharField(max_length=8, min_length=3, label='密码',
                          error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'},
                          widget=forms.widgets.PasswordInput(attrs={'class':'form-control','id':'basic-addon2'}))
    # 校验邮箱格式
    email = forms.EmailField(label='邮箱', required=True, error_messages={'invalid': '必须是邮箱格式啊~我的哥'},
                             widget=forms.widgets.EmailInput(attrs={'class':'form-control','id':'basic-addon3'}))


def index3(request):
    if request.method == 'GET':
        myform = MyForm()
    elif request.method == 'POST':
        myform = MyForm(request.POST)
    return render(request, 'index3.html', locals())

局部钩子


需求

如下图,在注册的时候,输入用户名,匹配数据库,如果存在则返回错误信息,登录用户名已被使用


添加新方法

代码语言:javascript复制
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.core.exceptions import ValidationError ## 导入异常

# Create your views here.

## forms组件数据校验功能
# 0.导入模块
from django import forms


# 1.是个类,先要继承Form
class MyForm(forms.Form):
    # 2.定义一个属性可以校验字符串类型
    # 限制字符串,最大长度是8最小长度是3
    name = forms.CharField(max_length=8, min_length=3, label='用户',
                           error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'},
                           widget=forms.widgets.TextInput(attrs={'class':'form-control'}))
    pwd = forms.CharField(max_length=8, min_length=3, label='密码',
                          error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'},
                          widget=forms.widgets.PasswordInput(attrs={'class':'form-control','id':'basic-addon2'}))
    # 校验邮箱格式
    email = forms.EmailField(label='邮箱', required=True, error_messages={'invalid': '必须是邮箱格式啊~我的哥'},
                             widget=forms.widgets.EmailInput(attrs={'class':'form-control','id':'basic-addon3'}))

    def clean_name(self):
        name = self.cleaned_data.get('name')
        if name.startswith('sb'):
            # 失败,抛异常
            raise ValidationError('不能以傻逼开头')
        #  成功就返回
        return name


def index3(request):
    if request.method == 'GET':
        myform = MyForm()
    elif request.method == 'POST':
        myform = MyForm(request.POST)
    return render(request, 'index3.html', locals())

全局钩子


需求

注册页面再来一个确认密码,保证两次密码输入的一致。

重写clean方法


添加新方法

代码语言:javascript复制
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.core.exceptions import ValidationError ## 导入异常

# Create your views here.

## forms组件数据校验功能
# 0.导入模块
from django import forms


# 1.是个类,先要继承Form
class MyForm(forms.Form):
    # 2.定义一个属性可以校验字符串类型
    # 限制字符串,最大长度是8最小长度是3
    name = forms.CharField(max_length=8, min_length=3, label='用户',
                           error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'},
                           widget=forms.widgets.TextInput(attrs={'class':'form-control'}))
    pwd = forms.CharField(max_length=8, min_length=3, label='密码',
                          error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'},
                          widget=forms.widgets.PasswordInput(attrs={'class':'form-control','id':'basic-addon2'}))
    re_pwd = forms.CharField(max_length=8, min_length=3, label='确认密码',
                          error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'},
                          widget=forms.widgets.PasswordInput(attrs={'class': 'form-control', 'id': 'basic-addon2'}))
    # 校验邮箱格式
    email = forms.EmailField(label='邮箱', required=True, error_messages={'invalid': '必须是邮箱格式啊~我的哥'},
                             widget=forms.widgets.EmailInput(attrs={'class':'form-control','id':'basic-addon3'}))

    def clean_name(self):
        name = self.cleaned_data.get('name')
        if name.startswith('sb'):
            # 失败,抛异常
            raise ValidationError('不能以傻逼开头')
        #  成功就返回
        return name

    def clean(self):
        pwd = self.cleaned_data.get('pwd')
        re_pwd = self.cleaned_data.get('re_pwd')
        if pwd != re_pwd:
            raise ValidationError('两次密码不一致')


def index3(request):
    if request.method == 'GET':
        myform = MyForm()
    elif request.method == 'POST':
        myform = MyForm(request.POST)
        if myform.is_valid():
            print(myform.cleaned_data)
        else:
            print(myform.errors.as_data)
    return render(request, 'index3.html', locals())

实现在页面显示

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>渲染错误信息</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

</head>
<body>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>使用渲染模板的第二种方式渲染错误信息:</h1>
<form action="" method="post" novalidate>
    {% for foo in myform %}
        <div>{{ foo.label }}:{{ foo }} <span>{{ foo.errors.0 }}</span></div>
    {% endfor %}
    <input type="submit" value="提交"> <span>{{ all_error }}</span>
</form>
</body>
</html>
代码语言:javascript复制
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.core.exceptions import ValidationError ## 导入异常

# Create your views here.

## forms组件数据校验功能
# 0.导入模块
from django import forms


# 1.是个类,先要继承Form
class MyForm(forms.Form):
    # 2.定义一个属性可以校验字符串类型
    # 限制字符串,最大长度是8最小长度是3
    name = forms.CharField(max_length=8, min_length=3, label='用户',
                           error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'},
                           widget=forms.widgets.TextInput(attrs={'class':'form-control'}))
    pwd = forms.CharField(max_length=8, min_length=3, label='密码',
                          error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'},
                          widget=forms.widgets.PasswordInput(attrs={'class':'form-control','id':'basic-addon2'}))
    re_pwd = forms.CharField(max_length=8, min_length=3, label='确认密码',
                          error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'},
                          widget=forms.widgets.PasswordInput(attrs={'class': 'form-control', 'id': 'basic-addon2'}))
    # 校验邮箱格式
    email = forms.EmailField(label='邮箱', required=True, error_messages={'invalid': '必须是邮箱格式啊~我的哥'},
                             widget=forms.widgets.EmailInput(attrs={'class':'form-control','id':'basic-addon3'}))

    def clean_name(self):
        name = self.cleaned_data.get('name')
        if name.startswith('sb'):
            # 失败,抛异常
            raise ValidationError('不能以傻逼开头')
        #  成功就返回
        return name

    def clean(self):
        pwd = self.cleaned_data.get('pwd')
        re_pwd = self.cleaned_data.get('re_pwd')
        if pwd != re_pwd:
            raise ValidationError('两次密码不一致')


def index3(request):
    if request.method == 'GET':
        myform = MyForm()
    elif request.method == 'POST':
        myform = MyForm(request.POST)
        if myform.is_valid():
            print(myform.cleaned_data)
        else:
            all_error = myform.errors.get('__all__')[0]
            print(myform.errors.as_data)
    return render(request, 'index3.html', locals())

实现注册功能


模型层

创建表

models.py

代码语言:javascript复制
from django.db import models


# Create your models here.
class User(models.Model):
    name = models.CharField(max_length=32)
    pwd = models.CharField(max_length=32)
    email = models.EmailField()

数据库迁移

代码语言:javascript复制
MacBook-pro:formsssss driverzeng$ python3 manage.py makemigrations app01
MacBook-pro:formsssss driverzeng$ python3 manage.py migrate


路由层

代码语言:javascript复制
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index_form/', views.index_form),
    url(r'^index2/', views.index2),
    url(r'^index3/', views.index3),
]

视图层

注册成功就往数据库插入数据

views.py

代码语言:javascript复制
from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.core.exceptions import ValidationError  ## 导入异常
from app01 import models
# Create your views here.

## forms组件数据校验功能
# 0.导入模块
from django import forms


# 1.是个类,先要继承Form
class MyForm(forms.Form):
    # 2.定义一个属性可以校验字符串类型
    # 限制字符串,最大长度是8最小长度是3
    name = forms.CharField(max_length=8, min_length=3, label='用户',
                           error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'},
                           widget=forms.widgets.TextInput(attrs={'class': 'form-control'}))
    pwd = forms.CharField(max_length=8, min_length=3, label='密码',
                          error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'},
                          widget=forms.widgets.PasswordInput(attrs={'class': 'form-control', 'id': 'basic-addon2'}))
    re_pwd = forms.CharField(max_length=8, min_length=3, label='确认密码',
                             error_messages={'max_length': '老弟啊,最大是8位', 'min_length': '那啥最小是3位', 'required': '这个必须填'},
                             widget=forms.widgets.PasswordInput(attrs={'class': 'form-control', 'id': 'basic-addon2'}))
    # 校验邮箱格式
    email = forms.EmailField(label='邮箱', required=True, error_messages={'invalid': '必须是邮箱格式啊~我的哥'},
                             widget=forms.widgets.EmailInput(attrs={'class': 'form-control', 'id': 'basic-addon3'}))

    def clean_name(self):
        name = self.cleaned_data.get('name')
        if name.startswith('sb'):
            # 失败,抛异常
            raise ValidationError('不能以傻逼开头')
        #  成功就返回
        return name

    def clean(self):
        pwd = self.cleaned_data.get('pwd')
        re_pwd = self.cleaned_data.get('re_pwd')
        if pwd != re_pwd:
            raise ValidationError('两次密码不一致')


def index3(request):
    if request.method == 'GET':
        myform = MyForm()
    elif request.method == 'POST':
        myform = MyForm(request.POST)
        if myform.is_valid():
            # myform.cleaned_data是一个字典,但是会传过来re_pwd的字段,我们来把它删掉然后再传入
            myform.cleaned_data.pop('re_pwd')
            # models.User.objects.create(name='zls',pwd='123') 正常需要这么传入,我们可以直接传入字典
            models.User.objects.create(**myform.cleaned_data)
            ## 创建成功之后,跳转到登录页面,就不能return index3.html了,因为没有写登录页面,所以临时注册成功就跳转我博客http://blog.driverzeng.com
            return redirect('http://blog.driverzeng.com')
        else:
            ## 如果注册成功,all_error没有值,网页就会报错,所以我们给 all_error添加一个判断
            all_error = myform.errors.get('__all__')
            if all_error:
                all_error = all_error[0]
    return render(request, 'index3.html', locals())

前端

index3.html

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>渲染错误信息</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

</head>
<body>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>使用渲染模板的第二种方式渲染错误信息:</h1>
<form action="" method="post" novalidate>
    {% for foo in myform %}
        <div>{{ foo.label }}:{{ foo }} <span>{{ foo.errors.0 }}</span></div>
    {% endfor %}
    <input type="submit" value="提交"> <span>{{ all_error }}</span>
</form>
</body>
</html>

 注册成功

 跳转页面

 数据库中有数据

0 人点赞