1. 程式人生 > >Django之Forms元件

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>