Django组件之forms

forms:校验字段功能

针对一个实例:注册用户讲解。

模型:models.py

class UserInfo(models.Model):
    name=models.CharField(max_length=32)
    pwd=models.CharField(max_length=32)
    email=models.EmailField()
    tel=models.CharField(max_length=32)

模板: register.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

<form action="" method="post">
    {% csrf_token %}
    <div>
        <label for="user">用户名</label>
        <p><input type="text" name="name" id="name"></p>
    </div>
    <div>
        <label for="pwd">密码</label>
        <p><input type="password" name="pwd" id="pwd"></p>
    </div>
    <div>
        <label for="r_pwd">确认密码</label>
        <p><input type="password" name="r_pwd" id="r_pwd"></p>
    </div>
     <div>
        <label for="email">邮箱</label>
        <p><input type="text" name="email" id="email"></p>
    </div>
    <input type="submit">
</form>

</body>
</html>

视图函数:register

# forms组件
from django.forms import widgets

wid_01=widgets.TextInput(attrs={"class":"form-control"})
wid_02=widgets.PasswordInput(attrs={"class":"form-control"})

class UserForm(forms.Form):
    name=forms.CharField(max_length=32,
                         widget=wid_01
                         )
    pwd=forms.CharField(max_length=32,widget=wid_02)
    r_pwd=forms.CharField(max_length=32,widget=wid_02)
    email=forms.EmailField(widget=wid_01)
    tel=forms.CharField(max_length=32,widget=wid_01)

def register(request):

    if request.method=="POST":
        form=UserForm(request.POST)
        if form.is_valid():
            print(form.cleaned_data)       # 所有干净的字段以及对应的值
        else:
            print(form.cleaned_data)       #
            print(form.errors)             # ErrorDict : {"校验错误的字段":["错误信息",]}
            print(form.errors.get("name")) # ErrorList ["错误信息",]
        return HttpResponse("OK")
    form=UserForm()
    return render(request,"register.html",locals())

渲染标签功能

渲染方式1

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
   <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<h3>注册页面</h3>
<div class="container">
    <div class="row">
        <div class="col-md-6 col-lg-offset-3">

                <form action="" method="post">
                    {% csrf_token %}
                    <div>
                        <label for="">用户名</label>
                        {{ form.name }}
                    </div>
                    <div>
                        <label for="">密码</label>
                        {{ form.pwd }}
                    </div>
                    <div>
                        <label for="">确认密码</label>
                        {{ form.r_pwd }}
                    </div>
                    <div>
                        <label for=""> 邮箱</label>
                        {{ form.email }}
                    </div>

                    <input type="submit" class="btn btn-default pull-right">
                </form>
        </div>
    </div>
</div>

</body>
</html>

渲染方式2

<form action="" method="post">
                    {% csrf_token %}

                    {% for field in form %}
                        <div>
                            <label for="">{{ field.label }}</label>
                            {{ field }}
                        </div>
                    {% endfor %}
                    <input type="submit" class="btn btn-default pull-right">

</form>

渲染方式3

<form action="" method="post">
    {% csrf_token %}

    {{ form.as_p }}
    <input type="submit" class="btn btn-default pull-right">

</form>

显示错误与重置输入信息功能

视图

def register(request):

    if request.method=="POST":
        form=UserForm(request.POST)
        if form.is_valid():
            print(form.cleaned_data)       # 所有干净的字段以及对应的值
        else:
            print(form.cleaned_data)       #
            print(form.errors)             # ErrorDict : {"校验错误的字段":["错误信息",]}
            print(form.errors.get("name")) # ErrorList ["错误信息",]
        return render(request,"register.html",locals())
    form=UserForm()
    return render(request,"register.html",locals())

模板

<form action="" method="post" novalidate>
    {% csrf_token %}

    {% for field in form %}
        <div>
            <label for="">{{ field.label }}</label>
            {{ field }} <span class="pull-right" style="color: red">{{ field.errors.0 }}</span>
        </div>
    {% endfor %}
    <input type="submit" class="btn btn-default">

</form>

局部钩子与全局钩子

模板

# forms组件
from django.forms import widgets

wid_01=widgets.TextInput(attrs={"class":"form-control"})
wid_02=widgets.PasswordInput(attrs={"class":"form-control"})

from django.core.exceptions import ValidationError
class UserForm(forms.Form):
    name=forms.CharField(max_length=32,
                         widget=wid_01
                         )
    pwd=forms.CharField(max_length=32,widget=wid_02)
    r_pwd=forms.CharField(max_length=32,widget=wid_02)
    email=forms.EmailField(widget=wid_01)
    tel=forms.CharField(max_length=32,widget=wid_01)

    # 局部钩子
    def clean_name(self):
        val=self.cleaned_data.get("name")
        if not val.isdigit():
            return val
        else:
            raise ValidationError("用户名不能是纯数字!")

    # 全局钩子

    def clean(self):
        pwd=self.cleaned_data.get("pwd")
        r_pwd=self.cleaned_data.get("r_pwd")

        if pwd==r_pwd:
            return self.cleaned_data
        else:
            raise ValidationError(‘两次密码不一致!‘)

def register(request):

    if request.method=="POST":
        form=UserForm(request.POST)
        if form.is_valid():
            print(form.cleaned_data)       # 所有干净的字段以及对应的值
        else:
            clean_error=form.errors.get("__all__")
        return render(request,"register.html",locals())
    form=UserForm()
    return render(request,"register.html",locals())

视图

 <form action="" method="post" novalidate>
            {% csrf_token %}

            {% for field in form %}
                <div>
                    <label for="">{{ field.label }}</label>
                    {{ field }}
                    <span class="pull-right" style="color: red">
                          {% if field.label == ‘R pwd‘ %}
                          <span>{{ clean_error.0 }}</span>
                          {% endif %}
                          {{ field.errors.0 }}
                    </span>
                </div>
            {% endfor %}
            <input type="submit" class="btn btn-default">

</form>

原文地址:https://www.cnblogs.com/qq631243523/p/9897425.html

时间: 2024-09-29 05:05:31

Django组件之forms的相关文章

Django组件-cookie,session

昨日内容回顾: json 轻量级的数据交换格式 在python 序列化方法:json.dumps() 反序列化方法:json.loads() 在JS中: 序列化方法:JSON.stringfy() 反序列化方法:JSON.parse() ajax $.ajax({ url:"", type:"", data:{}, // 默认contentType="urlencoded" success:function(data){ } }) 一.Djang

Django组件——cookie与session

Django组件--cookie与session 一.会话跟踪技术 1.什么是会话跟踪技术 先了解一下什么是会话.可以把会话理解为客户端与服务器之间的一次会晤,在一次会晤中可能会包含多次请求和响应.例如你给10086打电话,你就是客户端,而10086服务人员就是服务器,从双方接通电话那一刻起,会话就开始了,到某一方挂断电话就表示会话结束.在通话过程中,你会向10086发出多个请求,这多个请求都在一个会话中. 在JavaWeb在,客户向某一服务器发出第一个请求开始,会话就开始了,直到客户关闭了浏览

Django组件—forms组件

forms组件: 校验字段功能: 针对一个实例:注册用户. 模型:models.py class UserInfo(models.Model): name=models.CharField(max_length=32) pwd=models.CharField(max_length=32) email=models.EmailField() tel=models.CharField(max_length=32) 模板:register.html <!DOCTYPE html> <html

12.Django组件-forms组件

forms组件 校验字段功能 针对一个实例:注册用户讲解. 模型:models.py class UserInfo(models.Model): name=models.CharField(max_length=32) pwd=models.CharField(max_length=32) email=models.EmailField() tel=models.CharField(max_length=32) 模板: register.html: <!DOCTYPE html> <ht

Django组件——forms组件

一,forms组件: 校验字段功能针对一个实例:注册用户讲解.模型:models.py class UserInfo(models.Model): name=models.CharField(max_length=32) pwd=models.CharField(max_length=32) email=models.EmailField() tel=models.CharField(max_length=32) 模板: register.html: <!DOCTYPE html> <h

Django组件:forms组件

针对"注册用户"示例: 一.校验字段功能 1.模型:models.py class UserInfo(models.Model): name=models.CharField(max_length=32) pwd=models.CharField(max_length=32) email=models.EmailField() tel=models.CharField(max_length=32) 2.模板:register.html: <!DOCTYPE html> &l

Django组件-forms

forms组件 一.app01.models.py ? 1 2 3 4 5 6 7 8 9 10 from django.db import models class UserInfo(models.Model):     nid = models.BigAutoField(primary_key=True)     name = models.CharField(verbose_name='用户名', max_length=32, unique=True)     pwd = models.C

Django框架之Forms组件(基于注册功能)

1.注册功能分析 注册功能 1.渲染前端标签获取用户输入 >>> 渲染标签 2.获取用户输入传递到后端校验 >>> 校验数据 3.校验未通过展示错误信息 >>> 展示信息 2.使用 forms 组件实现注册功能 1.校验数据 校验规则:form组件校验数据的规则从上往下依次取值校验    校验通过的放到cleaned_data    校验失败的放到errors from django import forms class MyForm(forms.Fo

ModelForm组件和forms组件补充

forms组件补充: forms组件的三个字段:ChoiceField, ModelChoiceField & ModelMultipleChoiceField # forms组件:ChoiceField,ModelChoiceField,ModelMultipleChoiceField:这三个可用于渲染 <select> 标签 gender = forms.ChoiceField(choices=((1,"男"),(2,"女"))) # 不与数