django form 表单实现前端认证以及显示错误信息

大致是这样的流程。代码实现

前端部分,没什么样式。只是单纯为了实现注册验证

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/bs/css/bootstrap.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-6 col-md-offset-4">
                <h1>注册</h1>
                <form method="post">
                    {% csrf_token %}
                    {% for field in from_obj %}
                        <div class="form-group">
                            <label for="id_{{ field.name }}">{{ field.label }}</label>
                            {{ field }}
                            <span class="error pull-right" style="color: red"></span>
                        </div>
                    {% endfor %}
                    <br>
                </form>
                <input type="button" value="提交" class="btn btn-default" id="send_ajax">
            </div>
        </div>
    </div>
    <script src="/static/js/jQuery-3.4.1.js"></script>
    <script>
        $('.btn').click(function () {
            $.ajax({
                    url: '',
                    type: 'post',
                    data: {
                        'username': $('#id_username').val(),
                        'pwd': $('#id_pwd').val(),
                        'r_pwd': $('#id_r_pwd').val(),
                        'email': $('#id_email').val(),
                        'tel': $('#id_tel').val(),
                        'csrfmiddlewaretoken': '{{ csrf_token }}'
                    },
                    success: function (data) {
                        
                        if (data.user) {
                            console.log(222);
                            location.href='/index/'
                        }
                        else {
                            $.each(data.msg, function (errorms,errorm_list) {
                                $('span').html('');
                                if(errorms=='__all__'){
                                    $('#id_r_pwd+span').text(errorm_list[0]).parent().addClass('has-error')
                                }
                                $('#id_'+errorms).next().html(errorm_list[0])

                            })

                        }

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

views

from django.shortcuts import render
from django.http import JsonResponse
from t_from.dt_from import dt_froms
from t_from import models

# Create your views here.

def dt_from(request):

    from_obj = dt_froms.my_from()
    if request.is_ajax():
        from_obj = dt_froms.my_from(request.POST)
        response = {'user': None, 'msg': None}
        # 通过校验
        if from_obj.is_valid():
            response['user'] = from_obj.cleaned_data.get('username')
            models.User.objects.create(
                username=from_obj.cleaned_data.get('username'),
                password=from_obj.cleaned_data.get('pwd'),
                email=from_obj.cleaned_data.get('email'),
                tel=from_obj.cleaned_data.get('tel'),
            )
        else:
            response['msg'] = from_obj.errors
        return JsonResponse(response)
    return render(request,'registered.html',locals())

form组件

from django import forms
from django.forms import widgets
from django.core.exceptions import ValidationError
import re

from t_from import models as dt_models

css_style_01 = widgets.TextInput(attrs={'class':"form-control"})
css_style_02 = widgets.PasswordInput(attrs={'class':"form-control"})

# 创建from组件
class my_from(forms.Form):

    username = forms.CharField(min_length=6, label='账号', widget=css_style_01)

    pwd = forms.CharField(min_length=6, label='密码', widget=css_style_02,
                          error_messages={'required': '密码不能为空.',
                                          'invalid': '密码必须包含数字,字母、特殊字符',
                                          'min_length': '密码长度不能小于6个字符',
                                          'max_length': '密码长度不能大于32个字符',
                                          }
                          )
    r_pwd = forms.CharField(min_length=6, label='确认密码', widget=css_style_02,
                            error_messages={'required': '密码不能为空.',
                                            'invalid': '密码必须包含数字,字母、特殊字符',
                                            'min_length': '密码长度不能小于6个字符',
                                            'max_length': '密码长度不能大于32个字符',
                                            }
                            )
    email = forms.EmailField(label='邮箱', widget=css_style_01,
                             error_messages={
                                 'required': '邮箱不能为空',
                                 'invalid': '邮箱格式错误',
                             }
                             )
    tel = forms.IntegerField(label='电话号码', widget=css_style_01,
                             error_messages={
                                 'required': '电话不能为空',
                                 'invalid': '电话格式不正确',
                             }
                             )

    # 局部钩子
    def clean_username(self):
        val = self.cleaned_data.get("username")
        if re.fullmatch(r'^\d+$', val):
            raise ValidationError('用户名字不能是纯数字')
        elif dt_models.User.objects.filter(username=val):
            raise ValidationError('该用户已经存在')
        else:
            return val


    # 全局钩子
    def clean(self):
        if self.cleaned_data.get("pwd") == self.cleaned_data.get("r_pwd"):
            return self.cleaned_data

        else:
            raise ValidationError('两次密码不一致!')

models

from django.db import models

# Create your models here.

class User(models.Model):

    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)
    email = models.EmailField(max_length=32)
    tel = models.IntegerField()

猜你喜欢

转载自www.cnblogs.com/dtaxx-99/p/13202131.html