1. 程式人生 > >Django中Form驗證

Django中Form驗證

tex -s AR action doctype color messages forms 大於

Django的Form主要具有一下幾大功能:

  • 生成HTML標簽
  • 驗證用戶數據(顯示錯誤信息)
  • HTML Form提交保留上次提交數據
  • 初始化頁面顯示內容

一,Form驗證

第一種操作:主要是這三個函數

is_valid()

cleaned_data

errors

from xiaoqing import  models

def form(request):

    if request.method == "GET":
        return render(request,form.html)
    elif request.method == "POST":
        obj 
= FM(request.POST) r1 = obj.is_valid() #is_valid() 讓這個函數去驗證 返回False 或者 True print(r1) if r1: print(r1) print(obj.cleaned_data) #cleaned_data表示返回的正確的信息 # models.Host.objects.create(**obj.cleaned_data) else: print(obj.errors.as_json()) #
errors表示錯誤信息 return render(request,form.html,{obj:obj,}) return redirect(/xiaoqing/host)
技術分享圖片
    <form action="/xiaoqing/form/" method="post">
        {% csrf_token %}
{#        {% for row in error_dict.keys %}#}
        <p><input type="text" placeholder="請輸入用戶名" name="
user"/><span style="color: red">{{ obj.errors.user.0 }}</span></p> <p><input type="password" placeholder="請輸入密碼" name="pwd"/><span style="color: red">{{ obj.errors.pwd.0 }}</span></p> <p><input type="text" placeholder="請輸入郵箱" name="email"/><span style="color: red">{{ obj.errors.email.0 }}</span></p> <input type="submit" value="提交"/> {# {% endfor %}#} </form>
form.html

第二種操作:如果驗證錯誤,用戶信息不會消失

技術分享圖片
def form(request):

    if request.method == "GET":
        obj = FM()   #第一次用GET請求時,需要返回客戶端一個對象

        return render(request,form.html,{obj:obj})  

    elif request.method == "POST":
        obj = FM(request.POST)
        r1 = obj.is_valid()     #is_valid() 讓這個函數去驗證  返回False 或者 True
        print(r1)
        if r1:
            print(r1)
            print(obj.cleaned_data)  #cleaned_data表示返回的正確的信息
            # models.Host.objects.create(**obj.cleaned_data)
        else:
            print(obj.errors.as_json())     #errors表示錯誤信息

            return render(request,form.html,{obj:obj,})
        return redirect(/xiaoqing/host)
views.py 技術分享圖片
        <form action="/xiaoqing/form/" method="post">
        {% csrf_token %}
{#        {% for row in error_dict.keys %}#}
        <p>{{ obj.user }}<span style="color: red">{{ obj.errors.user.0 }}</span></p>
        <p>{{ obj.pwd }}<span style="color: red">{{ obj.errors.pwd.0 }}</span></p>
        <p>{{ obj.email }}<span style="color: red">{{ obj.errors.email.0 }}</span></p>
        <input type="submit" value="提交"/>
{#        {% endfor %}#}
        </form>
form.html

二,Form 自定義樣式

from django import forms
from django.forms import widgets  # 需要import 插件widgets
from django.forms import fields   #用fields 做字段驗證


class FM(forms.Form):
    #字段本身只做驗證 它不生成input標簽
    user = fields.CharField(error_messages={required:用戶名不能為空},
                           widget=widgets.Textarea(attrs={class:c1}))  #用attrs 自定義樣式
    pwd = fields.CharField(max_length=12,
                          min_length=6,
                          error_messages={required:密碼不能為空,min_length:密碼長度不能小於6,max_length:密碼長度不能大於12},
                          widget=widgets.PasswordInput)  
    email = fields.EmailField(error_messages={required:郵箱不能為空,invalid:郵箱格式錯誤})
技術分享圖片
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .c1 {
            background-color: indianred;

        }

    </style>

</head>
<body>

<div>

{#    <form action="/xiaoqing/form/" method="post">#}
{#        {% csrf_token %}#}
{#        {% for row in error_dict.keys %}#}
{#        <p><input type="text" placeholder="請輸入用戶名" name="user"/><span style="color: red">{{ obj.errors.user.0 }}</span></p>#}
{#        <p><input type="password" placeholder="請輸入密碼" name="pwd"/><span style="color: red">{{ obj.errors.pwd.0 }}</span></p>#}
{#        <p><input type="text" placeholder="請輸入郵箱" name="email"/><span style="color: red">{{ obj.errors.email.0 }}</span></p>#}
{#        <input type="submit" value="提交"/>#}
{#        {% endfor %}#}
{#    </form>#}
{##}


        <form action="/xiaoqing/form/" method="post">
        {% csrf_token %}
{#        {% for row in error_dict.keys %}#}
        <p>{{ obj.user }}<span style="color: red">{{ obj.errors.user.0 }}</span></p>
        <p>{{ obj.pwd }}<span style="color: red">{{ obj.errors.pwd.0 }}</span></p>
        <p>{{ obj.email }}<span style="color: red">{{ obj.errors.email.0 }}</span></p>
        <input type="submit" value="提交"/>
{#        {% endfor %}#}
        </form>
    

</div>

</body>
</html>
form.html

Django中Form驗證