1. 程式人生 > >django form外掛簡單使用

django form外掛簡單使用

首先HTML效果圖:

HTML程式碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>註冊內容驗證</title>
</head>
<body>
    <form action="/register/" method="post" novalidate>
        <p>username:{{ obj.username }}{{ obj.errors.username.0 }}</p>
        <p>password:{{ obj.password }}{{ obj.errors.password.0 }}</p>
        <p>age:{{ obj.age }}{{ obj.errors.age.0 }}</p>
        <p>email:{{ obj.email }}{{ obj.errors.email.0 }}</p>
        <p>address:{{ obj.address }}{{ obj.errors.address.0 }}</p>
        <p>{{ obj.gender }}</p>
        <p>{{ obj.users }}</p>
        <p>{{ obj.myaddrs }}</p>
        <p><input type="submit" value="提交"><input type="reset" value="重置"> </p>
    </form>
</body>
</html>

 

後臺Veiws程式碼:

from django.shortcuts import render,redirect
from django import forms
from django.forms import widgets
# Create your views here.
#建立Form驗證類,繼承forms.Form
class RegisterForm(forms.Form):
    username = forms.CharField(max_length=32,min_length=12,required=True,error_messages={
        "max_length":"長度必須為6~12",
        "min_length":"長度必須為6~12",
        "required":"使用者名稱不能為空",
    })
    password = forms.CharField(required=True,error_messages={
        "required":"密碼不能為空!"
    })
    age = forms.IntegerField(required=True,error_messages={
        "required": "密碼不能為空!",
        "invalid":"年齡必須為數字!"
    })
    email = forms.EmailField(required=True,error_messages={
        "required": "郵箱不能為空!",
        "invalid": "郵箱格式不正確!"
    })
    address = forms.CharField(
        initial=2,
        widget = widgets.Select(choices=((1,"北京"),(2,"上海"),(3,"深圳"),))

    )

    gender = forms.ChoiceField(
        choices=((0,"男"),(1,"女")),
        widget=widgets.RadioSelect,
        initial=0
    )

    #多選select,值為列表
    users = forms.MultipleChoiceField(
        choices=((1,'上海'),(2,'北京'),(3,"深圳")),
        initial=[2,],
        #可以加屬性
        widget=widgets.SelectMultiple(attrs={"class":"ray"})
    )

    myaddrs = forms.MultipleChoiceField(
        choices=((1, '上海'), (2, '北京'), (3, "深圳")),
        initial=3,
        widget=widgets.CheckboxSelectMultiple
    )


def register(request):
    if request.method=="GET":
        obj = RegisterForm()
        return render(request,"registervalid.html",{"obj":obj})
    else:
        #將表單值獲取到 傳入Form引數
        obj = RegisterForm(request.POST)
        if obj.is_valid():
            print("驗證成功!",obj.cleaned_data)
            return redirect("Http://www.baidu.com")
        else:
            print("驗證失敗!",obj.errors)
            return render(request,"registervalid.html",{"obj":obj})