經過Django中的forms類對前臺的forms表單數據進行校驗

1.前端form表單模板代碼html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
    <form action="/login/" method="post">
        {% csrf_token %}
        {{obj.user}}<span>{{obj.errors.user.0}}</span>
        <br>
        {{obj.email}}<span>{{obj.errors.email.0}}</span>
        <br>
        <span>密碼</span><input type="text" name="password">
        <br>
        <input type="submit">
    </form>
</body>
</html>

2.後臺數據Python代碼對前端的form表單數據進行校驗前端

 1 from django.shortcuts import render, HttpResponse, redirect
 2 from django import forms
 3 
 4 # Create your views here.
 5 class Login(forms.Form):
 6     user = forms.CharField(min_length=6, error_messages={'required': '用戶名不能爲空', 'min_length': '用戶名不能小於6位'})
 7     email = forms.EmailField(error_messages={'required': '郵箱不能爲空', 'invalid': '郵箱格式錯誤'})
 8   #此處未定義password,會致使下面的Login對象在接收前臺數據時,只接收user數據和password數據
 9 
10 def login(request):
11     if request.method == 'GET':
12         obj = Login()
13         return render(request, 'login.html', {'obj': obj})
14     else:
15         obj = Login(request.POST)
16         if obj.is_valid():#is_valid()用於判斷obj對象是否校驗經過,校驗經過傳回true
17             value_list = obj.clean()#clean()用於獲取obj中已校驗經過的數據
18             print(value_list)
19             #create(**value_list)#可直接將獲取到的對象的值經過該方式插入到數據庫中
20         else:
21             #error_obj = obj.errors.as_json()#獲取校驗失敗的信息
22        error_obj = obj.errors #獲取錯誤對象
23        print(error_obj['user'][0])#獲取user中文錯誤信息
24        print(error_obj['email'][0])#獲取email中文錯誤信息
25             #print(error_obj)
26           return render(request, 'login.html', {'obj': obj})

 3.經過django生成前端form表單時,能夠經過widget自定義input輸入框的類型,並給它賦予前端屬性數據庫

 1 from django import forms
 2 from django.forms import fields
 3 from django.forms import widgets
 4 
 5 class LoginForm(forms.Form):
 6     user = fields.CharField(widget=widgets.TextInput(attrs={'class': 'hid', 'placeholder': '用戶名'}))
 7     #CharField的默認類型爲TextInput,此處加上只是爲了給當前input輸入框增長屬性attrs={'class': 'hid', 'placeholder': '用戶名'}
 8     password = fields.CharField(widget=widgets.PasswordInput(attrs={'class': 'hid', 'placeholder': '密碼'}))
 9     #CharField的默認類型爲TextInput,加上widget=widgets.PasswordInput後變成password類型輸入框
10     select = fields.ChoiceField(choices=[(1, 'SH'), (2, 'BJ'), ])
11     #利用choices=[(1, 'SH'), (2, 'BJ'), ]給前端下拉列表增長可選值

 4.經過models中的class類生成對應的form表單django

1 from django import forms
2 from app01 import models #導入表模型類
3 class UserInfoModelForm(forms.ModelForm):
4     class Meta:
5         model = models.Test #test爲models中的一個類
6         #fields = ('username',)
7         fields = '__all__'
相關文章
相關標籤/搜索