码迷,mamicode.com
首页 > 其他好文 > 详细

Django框架之forms组件

时间:2021-03-30 13:27:09      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:input   none   message   cep   star   code   提交   one   char   

forms组件之校验字段

# 第一步:定义一个类,继承forms.Form
# 第二步:在类中写字段,要校验的字段,字段属性就是校验规则
# 第三步:实例化得到一个Form对象,把要校验的数据传入
# 第四步:调用register_form.is_valid()校验,校验通过就是True
# 第五步:校验通过有register_form.cleaned_data
# 第六步:校验不通过 register_form.errors
技术图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册用户</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-md-6 col-md-offset-3">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">注册功能</h3>
        </div>
        <div class="panel-body">
            <h1 class="text-center">注册</h1>
            <form action="" method="post">
                <p>用户名:<input type="text" name="name" class="form-control"></p>
                <p>密码:<input type="password" name="password" class="form-control"></p>
                <p>确认密码:<input type="password" name="re_password" class="form-control"></p>
                <p>邮箱:<input type="text" name="email" class="form-control"></p>
                <input id="id_btn" type="submit" class="btn btn-primary btn-block">
        </div>
    </div>
</div>
</body>
</html>
校验手动渲染示例html
技术图片
class User(models.Model):
    name = models.CharField(max_length=32,verbose_name=用户名)
    password = models.CharField(max_length=32,verbose_name=密码)
    email = models.EmailField(verbose_name=邮箱)
创建用户表models.py
# views.py

from django.shortcuts import render
from django import forms

#定义类
class RegisterForm(forms.Form):
    # name字符串类型最大8位,最小3位
    name = forms.CharField(max_length=8, min_length=3, label=用户名)
    # password字符串类型最大8位,最小3位
    password = forms.CharField(max_length=8, min_length=3, label=密码)
    # re_password字符串类型最大8位,最小3位
    re_password = forms.CharField(max_length=8, min_length=3, label=确认密码)
    # email必须符合邮箱格式,xxx@xx.com
    email = forms.EmailField(label=邮箱)
   

#在视图中使用
register_form = RegisterForm(request.POST)
if register_form.is_valid():
      # 校验通过,存
      # 取出校验通过的数据
      print(校验通过)
      print(register_form.cleaned_data)
    
        # 存储前先删除多余的字段
        register_form.cleaned_data.pop(re_password)
       # 将数据存入数据库的user表中
       models.User.objects.create(**register_form.cleaned_data)
        
else:
     # 校验不通过
     print(校验不通过)
     print(register_form.errors)

forms组件之渲染标签

技术图片
def register(request):
    if request.method == GET:
        # GET请求没有数据,需要生成一个空form对象
        # 这个form跟下面没有关系,是get请求过来的得到一个空form
        register_form = RegisterFrom()
        # 传到前端页面后,通过form进行渲染
        return render(request, register.html, {form: register_form})
    else:
        register_form = RegisterFrom(request.POST)

        if register_form.is_valid():
            print(效验通过)
            print(register_form.cleaned_data)
            register_form.cleaned_data.pop(re_password)
            models.User.objects.create(**register_form.cleaned_data)
        else:
            print(效验不通过)
            print(register_form.errors)

        return render(request,register.html)
视图层:views.py

渲染方式一

可扩展性强,但是需要书写的代码太多,一般情况下不用

 <h2>通过form自动渲染一</h2>
<form action="" method="post">
     <p>用户名 {{ form.name }}</p>   
     <p>密码 {{ form.password }}</p>    
    <p>确认密码 {{ form.re_password }}</p>    
    <p>邮箱 {{ form.email }}</p>    
<input type="submit" value="提交">?</form>

渲染方式二

推荐使用,代码书写简单,并且可扩展性强

<h2>通过form自动渲染二(基本用这种)</h2>

<form action="" method="post">
    {% for item in form %}
        <p>{{ item.label }}{{ item }}</p>                    
    {% endfor %}
<input type="submit" value="提交"><span style="color: red">{{ error }}</span>

</form>

渲染方式三

代码书写极少,封装程度太高,不便于后续的扩展,一般情况下只在本地测试使用

<h2>通过form自动渲染三</h2>
<form action="" method="post">
    {{ form.as_p }}
    {#    {{ form.as_table }}#}
    {#    {{ form.as_ul }}#}

</form>

技术图片

forms组件之渲染错误信息

前端渲染代码:(全部采用方式二)

技术图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册页面</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-md-6 col-md-offset-3">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title text-center"></h3>
        </div>
        <div class="panel-body">
            <h1 class="text-center">注册</h1>
            <form action="" method="post" novalidate>
                {% for item in form %}
                    <div class="form-group">
                        <p>{{ item.label }}{{ item }} <span style="color: red">{{ item.errors.0 }}</span></p>
                    </div>

                {% endfor %}
                <input type="submit" value="提交" class="form-control"><span style="color: red">{{ error }}</span>

            </form>
        </div>
    </div>
</div>

</body>
</html>
html页面

后端views中定义form类:

from django import forms
from django.forms import widgets

class RegisterForm(forms.Form):
    name = forms.CharField(max_length=8, min_length=3, label=用户名,
                           error_messages={
                               max_length: 用户名最长为8位,
                               min_length: 用户名最短为3位,
                               required: 用户名不能为空位
                           },
                           widget=widgets.TextInput(attrs={class:form-control}))

    password = forms.CharField(max_length=8, min_length=3, label=密码,
                               error_messages={
                                   max_length: 密码最长为8位,
                                   min_length: 密码最短为3位,
                                   required: 密码不能为空
                               },
                               widget=widgets.PasswordInput(attrs={class:form-control}))

    re_password = forms.CharField(max_length=8, min_length=3, label=确认密码,
                                  error_messages={
                                      max_length : 密码最长为8位,
                                      min_length : 密码最短为3位,
                                      required : 密码不能为空
                                  },
                                  widget=widgets.PasswordInput(attrs={class:form-control}))

    email = forms.EmailField(label=邮箱,
                             error_messages={required: 邮箱不能为空, invalid: 邮箱格式不正确},
                             widget=widgets.TextInput(attrs={class:form-control}))


# views视图函数处理部分:  
def register(request):
    if request.method == GET:
        register_form = RegisterForm()
        return render(request, register.html, {form: register_form})
    else:
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            print(校验通过)
            print(register_form.cleaned_data)
            register_form.cleaned_data.pop(re_password)
            models.User.objects.create(**register_form.cleaned_data)
            return HttpResponse(ok)
        else:
            # 校验不通过
            print(校验不通过)
            print(register_form.errors)

            return render(request, register.html, {form: register_form})    

技术图片

forms组件参数配置

class Ret(Form):
    name = forms.CharField(max_length=10, min_length=2, label=用户名,
                           error_messages={
                               required: 该字段不能为空,
                               invalid: 格式错误, 
                               max_length: 太长,
                               min_length: 太短},
                           widget=widgets.TextInput(attrs={class:form-control}))

forms组件局部钩子,全局钩子

注意点:局部钩子拿什么,校验通过就返回什么。全局钩子拿什么,校验通过返回所有

局部钩子

 def clean_name(self):  # name字段的局部钩子
        # 获取用户输入的用户名
        name = self.cleaned_data.get(name)
        # 校验名字不能以sb开头
        if name.startswith(sb):
            # 校验不通过,必须抛异常,
            raise ValidationError(不能以sb开头)
        else:
            # 校验通过,再返回name对应的值
            return name

技术图片

全局钩子

  def clean(self):   # 全局钩子
        password = self.cleaned_data.get(password)
        re_password = self.cleaned_data.get(re_password)
        if re_password != password:
            # 校验不通过
            self.add_error(re_password,两次密码不一致)
        else:
            # 局部钩子拿什么返回什么,全局钩子所有都返回
            return self.changed_data

技术图片

forms组件总代码

技术图片
from django.db import models

# 创建用户表
class User(models.Model):
    name = models.CharField(max_length=32,verbose_name=用户名)
    password = models.CharField(max_length=32,verbose_name=密码)
    email = models.EmailField(verbose_name=邮箱)
模型层models.py
技术图片
from django.conf.urls import url
from app01 import views

urlpatterns = [
    url(r^register/$,views.register)
]
路由层urls.py
技术图片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模板层注册页面</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h3 class="panel-title text-center"></h3>
                </div>
                <div class="panel-body">
                    <h1 class="text-center">注册</h1>
                    <form action="" method="post" novalidate>
                        {% for item in form %}
                            <div class="form-group">
                                <p>{{ item.label }}{{ item }} <span style="color: red">{{ item.errors.0 }}</span></p>
                            </div>

                        {% endfor %}
                        <input type="submit" value="提交" class="btn btn-primary btn-block"><span style="color: red">{{ error }}</span>

                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>
模板层register.html

视图层views中定义form类:

from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError

class RegisterForm(forms.Form):
    name = forms.CharField(max_length=8, min_length=3, label=用户名,
                           error_messages={
                               max_length: 用户名最长为8位,
                               min_length: 用户名最短为3位,
                               required: 用户名不能为空位
                           },
                           widget=widgets.TextInput(attrs={
                               class:form-control
                           }))

    password = forms.CharField(max_length=8, min_length=3, label=密码,
                               error_messages={
                                   max_length: 密码最长为8位,
                                   min_length: 密码最短为3位,
                                   required: 密码不能为空
                               },
                               widget=widgets.PasswordInput(attrs={
                                   class:form-control
                               }))

    re_password = forms.CharField(max_length=8, min_length=3, label=确认密码,
                                  error_messages={
                                      max_length : 密码最长为8位,
                                      min_length : 密码最短为3位,
                                      required : 密码不能为空
                                  },
                                  widget=widgets.PasswordInput(attrs={
                                      class:form-control
                                  }))

    email = forms.EmailField(label=邮箱,
                             error_messages={
                                 required: 邮箱不能为空,
                                 invalid: 邮箱格式不正确
                             },
                             widget=widgets.TextInput(attrs={
                                 class:form-control
                                 
                                 
    def clean_name(self):  # name字段的局部钩子
        # 获取用户输入的用户名
        name = self.cleaned_data.get(name)
        # 校验名字不能以sb开头
        if name.startswith(sb):
            # 校验不通过,必须抛异常,
            raise ValidationError(不能以sb开头)
        else:
            # 校验通过,再返回name对应的值
            return name

    def clean(self):   # 全局钩子
        password = self.cleaned_data.get(password)
        re_password = self.cleaned_data.get(re_password)
        if re_password != password:
            # 校验不通过
            self.add_error(re_password,两次密码不一致)
        else:
            # 局部钩子拿什么返回什么,全局钩子所有都返回
            return self.changed_data



from app01 import models


def register(request):
    if request.method == GET:
        # GET请求没有数据,需要生成一个空form对象
        # 这个form跟下面没有关系,是get请求过来的得到一个空form
        register_form = RegisterFrom()
        # 传到前端页面后,通过form进行渲染
        return render(request, register.html, {form: register_form})

    else:
        # 实例化得到对象,传入要校验的数据
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            # 校验通过,存
            # 取出校验通过的数据
            print(校验通过)
            print(register_form.cleaned_data)
            register_form.cleaned_data.pop(re_password)
            models.User.objects.create(**register_form.cleaned_data)
            return HttpResponse(ok)

        else:
            # 校验不通过
            print(校验不通过)
            print(register_form.errors)
          
            return render(request, register.html, {form: register_form})

 

Django框架之forms组件

标签:input   none   message   cep   star   code   提交   one   char   

原文地址:https://www.cnblogs.com/gfeng/p/14590589.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!