1. 程式人生 > >後臺驗證插件forms(基於ajax傳輸數據)

後臺驗證插件forms(基於ajax傳輸數據)

最小值 註冊 基礎 tin widgets stringify _for trap lse

1.視圖函數

from django.shortcuts import render, HttpResponse,redirect,reverse
from django import forms
from django.forms import widgets
import json
from django.core.exceptions import ValidationError
from loginapp import models


# Create your views here.

class Login_forms(forms.Form):
    user = forms.CharField(max_length=10, min_length=3, label=‘用戶名‘, required=True,
                           widget=widgets.TextInput(attrs={‘id‘: ‘user‘,‘class‘:‘col-md-6‘}),
                           error_messages={‘max_length‘:‘最大長度為10‘,‘min_length‘:‘最短長度為3‘,‘required‘:‘不能為空‘})
    pwd = forms.CharField(max_length=20, min_length=3, label=‘密碼‘, required=True,
                          widget=widgets.PasswordInput(attrs={‘id‘: ‘pwd‘,‘class‘:‘col-md-6‘}),
                          error_messages={‘max_length‘:‘最大長度為20‘,‘min_length‘:‘最短長度為3‘,‘required‘:‘不能為空‘})
    pwd_rs = forms.CharField(max_length=20, min_length=3, label=‘確認密碼‘, required=True,
                             widget=widgets.PasswordInput(attrs={‘id‘: "pwd2",‘class‘:‘col-md-6‘}),
                             error_messages={‘max_length‘: ‘最大長度為20‘, ‘min_length‘: ‘最短長度為3‘, ‘required‘: ‘不能為空‘})
    email = forms.EmailField(label=‘郵箱‘, required=True,
                             widget=widgets.EmailInput(attrs={‘id‘: "email",‘class‘:‘col-md-6‘}),
                             error_messages={‘required‘:‘不能為空!‘,‘invalid‘: ‘不符合郵箱格式‘})
    def clean(self):
        pwd = self.cleaned_data.get(‘pwd‘)
        pwd_rs = self.cleaned_data.get(‘pwd_rs‘)
        if pwd == pwd_rs:
            return self.cleaned_data
        else:
            raise ValidationError(‘兩次密碼不一致‘)
    def clean_user(self):
        user = self.cleaned_data.get(‘user‘)
        user_pd = models.User.objects.filter(user=user).first()
        if user_pd:
            raise ValidationError(‘用戶名已存在!‘)
        else:
            return user

def login(request):
    if request.method == "GET":
        forms = Login_forms()
    if request.method == ‘POST‘:
        msg_dic = json.loads(request.body.decode(‘utf-8‘))
        # print(msg_dic)
        forms = Login_forms(msg_dic)
        if forms.is_valid():
            forms.cleaned_data.pop(‘pwd_rs‘)
            # print(forms.cleaned_data)
            models.User.objects.create(**forms.cleaned_data)
            return HttpResponse(json.dumps(‘s‘))
        else:
            # print(forms.cleaned_data, ‘不通過‘)
            return HttpResponse(json.dumps(forms.errors))
    return render(request, ‘login.html‘, locals())

2.模板層

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>登錄</title>
    {% load static %}
    <script src={% static ‘jquery-3.3.1.js‘ %}></script>
    <script src="/static/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css">
</head>
<body>
<div class="row">
    <div class="col-md-6 col-md-offset-3">
        <h2>用戶註冊</h2>
        {% for form in forms %}
            <p>{{ form.label }}:</p>
            <p>{{ form }}<p id={{ form.name }}sp>&nbsp;</p></p>
        {% endfor %}
        <p id="res" class="col-md-8">&nbsp;</p>
        <button type="button" class="btn btn-success col-md-6" id="btn">註冊</button>

    </div>

</div>
</body>
<script>
    $(‘#btn‘).click(function () {
        var msg_dic = {
            ‘user‘: $(‘#user‘).val(),
            ‘pwd‘: $(‘#pwd‘).val(),
            ‘pwd_rs‘: $(‘#pwd2‘).val(),
            ‘email‘: $(‘#email‘).val()
        };
        msg_dic = JSON.stringify(msg_dic);
        $.ajax({
            url: ‘/login/‘,
            type: ‘post‘,
            contentType: ‘application/json‘,
            data: msg_dic,
            dataType: ‘json‘,
            success: function (data) {
                {#console.log(data);#}
                if (data == ‘s‘) {
                    {#console.log(typeof data);#}
                    location.href = ‘/cg/‘
                } else {
                    if (data.user) {
                        $(‘#usersp‘).text(data.user);
                    } else {
                        $(‘#usersp‘).html(‘&nbsp;‘);
                    }
                    if (data.pwd) {
                        $(‘#pwdsp‘).text(data.pwd);
                    } else {
                        $(‘#pwdsp‘).html(‘&nbsp;‘);
                    }
                    if (data.pwd_rs) {
                        $(‘#pwd_rssp‘).text(data.pwd_rs);
                    } else {
                        $(‘#pwd_rssp‘).html(‘&nbsp;‘);
                    }
                    if (data.email) {
                        $(‘#emailsp‘).text(data.email);
                    } else {
                        $(‘#emailsp‘).html(‘&nbsp;‘);
                    }
                    if (data.__all__) {
                        $(‘#res‘).text(data.__all__);
                    }else{
                        $(‘#res‘).html(‘&nbsp;‘);
                    }
                }

            }
        })
    })
</script>
</html>

3.基礎知識

字段參數

//字段參數
max_length=最大值
min_length=最小值
label=標簽label中字符
required=判斷是否可以為空 True不能為空 False可以為空
widget = 輸入框的屬性 widget=widgets.TextInput(attrs={‘id‘: ‘user‘, ‘class‘: ‘col-md-6‘})
error_messages= 錯誤信息 error_messages={‘max_length‘: ‘最大長度為10‘, ‘min_length‘: ‘最短長度為3‘, ‘required‘: ‘不能為空‘})

局部鉤子校驗

//定義一個函數,名字叫:clean_字段名字,內部,取出該字段,進行校驗,如果通過,將該字段返回,如果失敗,拋異常(ValidationError)
    def clean_user(self):
        user = self.cleaned_data.get(‘user‘)
        user_pd = models.User.objects.filter(user=user).first()
        if user_pd:
            raise ValidationError(‘用戶名已存在!‘)
        else:
            return user

全局鉤子校驗

//程序能走到該函數,前面校驗已經通過了,所以可以從cleaned_data中取出密碼和確認密碼
    def clean(self):
        pwd = self.cleaned_data.get(‘pwd‘)
        pwd_rs = self.cleaned_data.get(‘pwd_rs‘)
        if pwd == pwd_rs:
            return self.cleaned_data
        else:
            raise ValidationError(‘兩次密碼不一致‘)

後臺驗證插件forms(基於ajax傳輸數據)