1. 程式人生 > >django ---forms組件

django ---forms組件

版本 imp -s contain resp type del 復制代碼 container

  • 1 校驗字段功能
  • 2 渲染標簽功能
  • 3 渲染錯誤信息功能
  • 4 組件的參數配置
  • 5 局部鉤子
  • 6 全局鉤子
回到目錄

1 校驗字段功能

針對一個實例:註冊用戶講解。

模型:models.py

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

模版文件
技術分享圖片
復制代碼

<!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>
技術分享圖片
視圖函數:
技術分享圖片
# 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())
技術分享圖片 回到目錄

2 渲染標簽功能

渲染方式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>
技術分享圖片 技術分享圖片

回到目錄

3 渲染錯誤信息功能

視圖

技術分享圖片 技術分享圖片
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>
技術分享圖片 技術分享圖片

回到目錄

4 組件的參數配置

技術分享圖片
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}))
    pwd = forms.CharField(max_length=10, min_length=2, widget=widgets.PasswordInput(attrs={class:form-control}))
    email = forms.EmailField(label=郵箱, error_messages={required: 該字段不能為空, invalid: 格式錯誤})
技術分享圖片

回到目錄

5 局部鉤子

技術分享圖片
    
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
def clean_name(self): val=self.cleaned_data.get("name") ret=UserInfo.objects.filter(name=val) if not ret: return val else: raise ValidationError("該用戶已註冊!") def clean_tel(self): val=self.cleaned_data.get("tel") if len(val)==11: return val else: raise ValidationError("手機號格式錯誤")
技術分享圖片

回到目錄

6 全局鉤子

技術分享圖片
    def clean(self):
        pwd=self.cleaned_data.get(pwd)
        r_pwd=self.cleaned_data.get(r_pwd)

        if pwd and r_pwd:
            if pwd==r_pwd:
                return self.cleaned_data
            else:
                raise ValidationError(兩次密碼不一致)
        else:

            return self.cleaned_data
技術分享圖片

pwd_err=my_form.errors.get(__all__)
技術分享圖片
from django import forms

from django.forms import widgets
from app01.models import UserInfo

from django.core.exceptions import NON_FIELD_ERRORS, ValidationError

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"})
                        )
    r_pwd=forms.CharField(min_length=4,label="確認密碼",error_messages={"required":"該字段不能為空"},widget=widgets.TextInput(attrs={"class":"form-control"}))
    email=forms.EmailField(label="郵箱",error_messages={"required":"該字段不能為空","invalid":"格式錯誤"},widget=widgets.TextInput(attrs={"class":"form-control"}))
    tel=forms.CharField(label="手機號",widget=widgets.TextInput(attrs={"class":"form-control"}))


    def clean_name(self):

        val=self.cleaned_data.get("name")

        ret=UserInfo.objects.filter(name=val)

        if not ret:
            return val
        else:
            raise ValidationError("該用戶已註冊!")

    def clean_tel(self):

        val=self.cleaned_data.get("tel")

        if len(val)==11:

            return val
        else:
            raise  ValidationError("手機號格式錯誤")

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

        if pwd and r_pwd:
            if pwd==r_pwd:
                return self.cleaned_data
            else:
                raise ValidationError(兩次密碼不一致)
        else:

            return self.cleaned_data
myforms 技術分享圖片
from django.shortcuts import render,HttpResponse

# Create your views here.





from app01.myforms import *


def reg(request):

    if request.method=="POST":

        print(request.POST)

        #form=UserForm({"name":"yu","email":"[email protected]","xxxx":"alex"})


        form=UserForm(request.POST) # form表單的name屬性值應該與forms組件字段名稱一致

        print(form.is_valid()) # 返回布爾值

        if form.is_valid():
            print(form.cleaned_data)  # {"name":"yuan","email":"[email protected]"}
        else:
            print(form.cleaned_data)  # {"email":"[email protected]"}
            # print(form.errors)        # {"name":[".........."]}
            # print(type(form.errors))  # ErrorDict
            # print(form.errors.get("name"))
            # print(type(form.errors.get("name")))    # ErrorList
            # print(form.errors.get("name")[0])


            #   全局鉤子錯誤
            #print("error",form.errors.get("__all__")[0])
            errors=form.errors.get("__all__")


            return render(request,"reg.html",locals())

        ‘‘‘

        form.is_valid()   :返回布爾值
        form.cleaned_data :{"name":"yuan","email":"[email protected]"}
        form.errors       :{"name":[".........."]}

        ‘‘‘


    form=UserForm()

    return render(request,"reg.html",locals())
視圖函數 技術分享圖片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .error{
            color: red;
        }
    </style>
    <!-- 最新版本的 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>

<div class="container">

    <div class="row">
        <div class="col-md-6 col-lg-offset-3">

            {#<h3>簡單form</h3>#}
            {##}
            {##}
            {#<form action="" method="post" novalidate>#}
            {#    {% csrf_token %}#}
            {#    <p>用戶名<input type="text" name="name"></p>#}
            {#    <p>密碼 <input type="text" name="pwd"></p>#}
            {#    <p>確認密碼 <input type="text" name="r_pwd"></p>#}
            {#    <p>郵箱  <input type="text" name="email"></p>#}
            {#    <p>手機號 <input type="text" name="tel"></p>#}
            {#    <input type="submit">#}
            {##}
            {#</form>#}

            <hr>
            <h3>forms組件渲染方式1</h3>
            <form action="" method="post" novalidate>

                {% csrf_token %}
                <p>{{ form.name.label }}
                    {{ form.name }} <span class="pull-right error">{{ form.name.errors.0 }}</span>
                </p>
                <p>{{ form.pwd.label }}
                    {{ form.pwd }} <span class="pull-right error">{{ form.pwd.errors.0 }}</span>
                </p>
                <p>確認密碼
                    {{ form.r_pwd }} <span class="pull-right error">{{ form.r_pwd.errors.0 }}</span><span class="pull-right error">{{ errors.0 }}</span>
                </p>
                <p>郵箱 {{ form.email }} <span class="pull-right error">{{ form.email.errors.0 }}</span></p>
                <p>手機號 {{ form.tel }} <span class="pull-right error">{{ form.tel.errors.0 }}</span></p>
                <input type="submit">

            </form>

            {#<h3>forms組件渲染方式2</h3>#}
            {##}
            {#<form action="" method="post" novalidate>#}
            {#     {% csrf_token %}#}
            {##}
            {#    {% for field in form %}#}
            {##}
            {#        <div>#}
            {#            <label for="">{{ field.label }}</label>#}
            {#            {{ field }}#}
            {#        </div>#}
            {##}
            {#    {% endfor %}#}
            {##}
            {#     <input type="submit">#}
            {#</form>#}
            {##}
            {#<h3>forms組件渲染方式3</h3>#}
            {##}
            {#<form action="" method="post">#}
            {#     {% csrf_token %}#}
            {##}
            {#     {{ form.as_p }}#}
            {##}
            {#     <input type="submit">#}
            {#</form>#}


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

</body>
</html>
模版文件

------------https://www.cnblogs.com/liuqingzheng/articles/9509775.html

django ---forms組件