Django之Forms组件

Posted yuliangkaiyue

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django之Forms组件相关的知识,希望对你有一定的参考价值。

froms组件

校验字段

校验字段是forms组件最重要的功能。

以用户注册为例

模型

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)

模板

技术分享图片
<!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>
View Code

视图函数

 1 class Userform(forms.Form):
 2     name = forms.CharField(min_length=4)
 3     pwd = forms.CharField(min_length=4)
 4     re_pwd = forms.CharField(min_length=4)
 5     email = forms.EmailField()
 6     tel = forms.CharField(label=电话)
 7 
 8 def register(request):
 9 
10     if request.method=="POST":
11         form=UserForm(request.POST)        # 会按照相对应的字段进行匹配,字段可以在Userform的字段基础上多,不会出错,但是已有字段一个也不能少
12         if form.is_valid():          # 如果校验通过
13             print(form.cleaned_data)       # 所有干净的字段以及对应的值
14         else:
15             print(form.cleaned_data)       #
16             print(form.errors)             # ErrorDict : {"校验错误的字段":["错误信息",]}
17             print(form.errors.get("name")) # ErrorList ["错误信息",]
18         return HttpResponse("OK")
19     form=UserForm()
20     return render(request,"register.html",locals())

渲染标签功能

方式一

技术分享图片
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
 7     <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
 8 </head>
 9 <body>
10 <h3>注册页面</h3>
11 <div class="container">
12     <div class="row">
13         <div class="col-md-6 col-lg-offset-3">
14 
15                 <form action="" method="post">
16                     {% csrf_token %}
17                     <div>
18                         <label for="">用户名</label>
19                         {{ form.name }}
20                     </div>
21                     <div>
22                         <label for="">密码</label>
23                         {{ form.pwd }}
24                     </div>
25                     <div>
26                         <label for="">确认密码</label>
27                         {{ form.r_pwd }}
28                     </div>
29                     <div>
30                         <label for=""> 邮箱</label>
31                         {{ form.email }}
32                     </div>
33 
34                     <input type="submit" class="btn btn-default pull-right">
35                 </form>
36         </div>
37     </div>
38 </div>
39 
40 
41 
42 </body>
43 </html>
View Code

方式二

技术分享图片
 1 <form action="" method="post">
 2                     {% csrf_token %}
 3                     
 4                     {% for field in form %}
 5                         <div>
 6                             <label for="">{{ field.label }}</label>
 7                             {{ field }}
 8                         </div>
 9                     {% endfor %}
10                     <input type="submit" class="btn btn-default pull-right">
11                 
12 </form>
View Code

 

方式三

技术分享图片
1 <form action="" method="post">
2     {% csrf_token %}
3     
4     {{ form.as_p }}
5     <input type="submit" class="btn btn-default pull-right">
6 
7 </form>
View Code

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

 模板

 1 <form action="" method="post" novalidate>         
 2                 {% csrf_token %}
 3                 <p>{{ form.name.label }}
 4                     {{ form.name }} <span>{{ form.name.errors.0 }}</span>
 5                 </p>
 6                 <p>
 7                     {{ form.pwd.label }}
 8                     {{ form.pwd }}<span>{{ form.pwd.errors.0 }}</span>
 9                 </p>
10                 <div>
11                     确认密码{{ form.re_pwd }}<span>{{ form.re_pwd.errors.0 }}</span>
12                 </div>
13                 <div>
14                     邮箱<input type="email" class="form-control" name="email"><span>{{ form.email.errors.0 }}</span>
15                 </div>
16                 <div>
17                     电话<input type="text" class="form-control" name="tel"><span>{{ form.tel.errors.0 }}</span>
18                 </div>
19                 <input type="submit" class="btn btn-success">
20             </form>

注意:novalidate 一定要加上,不然浏览器会替你校验,校验效果不是自己设计的样子

视图

from django.shortcuts import render, HttpResponse
# form组件
from django import forms
from django.forms import widgets


class Userform(forms.Form):
    name = forms.CharField(min_length=4, label=用户名, error_messages={"required": "不能为空"},
                           widget=widgets.TextInput(attrs={class: form-control}))
    pwd = forms.CharField(min_length=4, label=密码,widget=widgets.PasswordInput(attrs={class: form-control}), error_messages={required: 不能为空})
    re_pwd = forms.CharField(min_length=4,widget=widgets.TextInput(attrs={class: form-control}))
    email = forms.EmailField(widget=widgets.EmailInput(attrs={class: form-control}))
    tel = forms.CharField(label=电话,widget=widgets.TextInput(attrs={class: form-control}))


def reg(request):
    if request.method == POST:

        form = Userform(request.POST)  # 模板中的name属性对应Userform的每一个字段,字段名与响应的name属性一致
        print(form.is_valid())
        if form.is_valid():
            print(form.cleaned_data)
        else:
            print(form.cleaned_data)
            print(form.errors)
            # print(form.errors.get(‘name‘)) # name不传值 <ul class="errorlist"><li>This field is required.</li></ul>
            # print(type(form.errors.get(‘name‘))) # <class ‘django.forms.utils.ErrorList‘>
            # print(form.errors.get(‘name‘)[0])  # 获取错误信息 This field is required.
            return render(request, reg.html, locals())
    form = Userform()
    return render(request, reg.html, {form: 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>

 

以上是关于Django之Forms组件的主要内容,如果未能解决你的问题,请参考以下文章

Django之forms组件

Django之forms组件

Django之Forms组件

Django组件之forms

Django之forms组件

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