Django之強大的Form功能


 

轉載: http://www.cnblogs.com/0820-zq/p/5807980.html

 

Form

Form的驗證思路

前端:form表單

后台:創建form類,當請求到來時,先匹配,匹配出正確和錯誤信息。

Django的Form驗證實例

創建project,進行基礎配置文件配置

settings.py

 

settings.py之csrf注銷

 

__init__.py

 

urls.py

 

views.account.py:

復制代碼
from django.shortcuts import render,HttpResponse
from app01.forms import Form1

def form1(request):
    if request.method=="POST":  #這里POST一定要大寫
        #通常獲取請求信息
        #request.POST.get("user",None)
        #request.POST.get("pwd",None)
        #獲取請求內容,做驗證
        f = Form1(request.POST)  #request.POST:將接收到的數據通過Form1驗證
        if f.is_valid():  #驗證請求的內容和Form1里面的是否驗證通過。通過是True,否則False。
            print(f.cleaned_data)  #cleaned_data類型是字典,里面是提交成功后的信息
        else:  #錯誤信息包含是否為空,或者符合正則表達式的規則
            print(type(f.errors),f.errors)  #errors類型是ErrorDict,里面是ul,li標簽
            return render(request,"account/form1.html",{"error":f.errors})
    return render(request,"account/form1.html")
復制代碼

 

html:

復制代碼
<body>
{#{{ error }}接收后台返回的錯誤信息封裝在ul,li標簽里面:#}
    {{ error }}
    <form action="/form1/" method="POST">
        <div>
            <input type="text" name="user" />
        </div>
        <div>
            <input type="text" name="pwd" />
        </div>
        <div>
            <input type="submit" value="提交" />
        </div>
    </form>
</body>
復制代碼

 

forms.py:

from django import forms

class Form1(forms.Form):
    user = forms.CharField()
    pwd = forms.CharField()

 

訪問頁面:

沒有輸入內容后提交,通過模板語言展示了錯誤信息

 

Django強大之form驗證時不用自定義錯誤信息就可以返回錯誤信息到前端以標簽方式展現。

.is_valid():返回True或者False

.cleaned_data:通過驗證后的數據

errors:
.error.get("user",None)error封裝所有的錯誤信息,如果沒有獲取到,默認為None。

如:

 

.error.get["pwd"]直接獲取到ul、li。

如:

 

 

 Form之精華版本

forms.py

from django import forms

class Form1(forms.Form):
    user = forms.CharField()
    pwd = forms.CharField()

 

HTML:

復制代碼
   <form action="/form1/" method="POST">
        <div class="input-group">
            {#接收后台傳過來的form對象,自動生成input標簽#}
            {{ form.user }}
            {#從后台傳過來的error是字典,直接{{ error.user.0 }}呈現錯誤信息#}
       {#如果后台返回了錯誤信息,將錯誤信息放入span標簽,在頁面顯示,否則不顯示#}
            {% if error.user.0 %}
            <span>{{ error.user.0 }}</span>
            {% endif %}
        </div>
        <div class="input-group">
            {{ form.pwd }}
            {% if error.pwd.0 %}
            <span>{{ error.pwd.0 }}</span>
            {% endif %}
        </div>
        <div>
            <input type="submit" value="提交" />
        </div>
    </form>
復制代碼

 

account.py

復制代碼
def form1(request):
    if request.method == "POST":
        f = Form1(request.POST)
        if f.is_valid():
            print(f.cleaned_data)
        else:
            return render(request,"account/form1.html",{"error":f.errors,"form":f})
    else:
        # 如果不是post提交數據,就不傳參數創建對象,並將對象返回給前台,直接生成input標簽,內容為空
        f = Form1()
        return render(request,"account/form1.html",{"form":f})
    return render(request,"account/form1.html")
復制代碼

注:

 

 頁面展示:

注:這里的input標簽是后端返回form對象到前端通過{{ form.xxx }}所創建的

 

更強大的功能:

 forms里面的字段:

復制代碼
required:是否可以為空。required=True 不可以為空,required=False 可以為空
max_length=4 最多4個值,超過不會顯示
min_length=2 至少兩個值,少於兩個會返回提示信息
error_messages={'required': '郵箱不能為空', 'invalid': '郵箱格式錯誤'}  自定義錯誤信息,invalid 是格式錯誤
widget=forms.TextInput(attrs={'class': 'c1'}) 給自動生成的input標簽自定義class屬性
widget=forms.Textarea()  生成Textarea標簽。widget默認生成input標簽
復制代碼

實戰:

models.py

復制代碼
from django.db import models

# Create your models here.
class Author(models.Model):
    """
    作者
    """
    name = models.CharField(max_length=100)
    age = models.IntegerField()

class BookType(models.Model):
    """
    圖書類型
    """
    caption = models.CharField(max_length=64)

class Book(models.Model):
    """
    圖書
    """
    name = models.CharField(max_length=64)
    pages = models.IntegerField()
    price = models.DecimalField(max_digits=10,decimal_places=2)
    pubdate = models.DateField()

    authors = models.ManyToManyField(Author)
    book_type = models.ForeignKey(BookType)
復制代碼

 

forms.py:

復制代碼
from django import forms
from app01 import models

class Form1(forms.Form):
    user = forms.CharField(
        widget=forms.TextInput(attrs={'class': 'c1'}),
        error_messages={'required': '用戶名不能為空'}, )
    pwd = forms.CharField(max_length=4, min_length=2,required=True)
    email = forms.EmailField(error_messages={'required': '郵箱不能為空', 'invalid': '郵箱格式錯誤'})

    memo = forms.CharField(
        widget=forms.Textarea()
    )
    #直接寫數據
    # user_type_choice = (
    #     (0, '普通用戶'),
    #     (1, '高級用戶'),
    # )
    #通過BookType表查詢信息,values_list拿到的是元組。id作為value顯示,caption作為text在頁面顯示
    # user_type_choice = models.BookType.objects.values_list('id', 'caption')
    # book_type = forms.CharField(
    #     widget=forms.widgets.Select(choices=user_type_choice, attrs={'class': "form-control"}))

    
    #寫上以下代碼就不用擔心數據庫添加了數據而不能及時獲取了
    def __init__(self, *args, **kwargs):
        #每次創建Form1對象時執行init方法
        super(Form1, self).__init__(*args, **kwargs)

        self.fields['book_type'] = forms.CharField(
            widget=forms.widgets.Select(choices=models.BookType.objects.values_list('id', 'caption'),
                                        attrs={'class': "form-control"}))
復制代碼

 

HTML:

復制代碼
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .input-group{
            position: relative;
            padding: 20px;
            width: 250px;
        }
        .input-group input{
            width: 200px;
            display: inline-block;
        }
        .inline-group span{
            display: inline-block;
            position: absolute;
            height: 12px;
            font-size: 8px;
            border: 1px solid red;
            background-color: coral;
            color: white;
            top: 41px;
            left: 20px;
            width: 202px;
        }
    </style>
</head>
<body>
    <form action="/form1/" method="POST">
        <div class="input-group">
{#            接收后台傳過來的form對象,自動生成input標簽#}
            {{ form.user }}
{#            從后台傳過來的error是字典,直接{{ error.user.0 }}呈現錯誤信息#}
{#            如果后台返回了錯誤信息,將錯誤信息放入span標簽,在頁面顯示,否則不顯示#}
            {% if error.user.0 %}
            <span>{{ error.user.0 }}</span>
            {% endif %}
        </div>
        <div class="input-group">
            {{ form.pwd }}
            {% if error.pwd.0 %}
            <span>{{ error.pwd.0 }}</span>
            {% endif %}
        </div>
        <div class="input-group">
            {{ form.email }}
            {% if error.email.0 %}
            <span>{{ error.email.0 }}</span>
            {% endif %}
        </div>
         <div class="input-group">
            {{ form.memo }}
            {% if error.memo.0 %}
            <span>{{ error.memo.0 }}</span>
            {% endif %}
        </div>
             <div class="input-group">
            {{ form.book_type }}
            {% if error.book_type.0 %}
            <span>{{ error.book_type.0 }}</span>
            {% endif %}
        </div>

        <div>
            <input type="submit" value="提交" />
        </div>
    </form>

</body>
</html>
復制代碼

 

account.py:

復制代碼
from django.shortcuts import render,HttpResponse
from app01.forms import Form1
from app01.models import *


# def test(req):
#     BookType.objects.create(caption='技術')
#     BookType.objects.create(caption='文學')
#     BookType.objects.create(caption='動漫')
#     BookType.objects.create(caption='男人裝')
#     return HttpResponse("ok")


def form1(request):
    if request.method == "POST":
        f = Form1(request.POST)
        if f.is_valid():
            print(f.cleaned_data)
        else:
            return render(request,"account/form1.html",{"error":f.errors,"form":f})
    else:
        # 如果不是post提交數據,就不傳參數創建對象,並將對象返回給前台,直接生成input標簽,內容為空
        f = Form1()
        return render(request,"account/form1.html",{"form":f})
    return render(request,"account/form1.html")
復制代碼

 

Django里面沒有手機驗證,沒有的需要自定義

示例:

Form
View


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM