BBS(第一天)项目之 注册功能实现通过forms验证与 前端ajax请求触发查询数据库判断用户是否存在的功能实现

1.BBS项目之注册功能通过forms验证

from django import forms
from blog.models import User
from django.contrib.auth import authenticate

class CheckForm(forms.Form):
    username = forms.CharField(max_length=10, min_length=3)
    password = forms.CharField(max_length=18, min_length=6)
    re_password = forms.CharField(max_length=18, min_length=6)
    telephone = forms.CharField(max_length=11, min_length=11)  #?
    email = forms.EmailField()

    def clean_username(self):

        cleaned_username = self.cleaned_data.get('username')


        return cleaned_username
forms简单编写与设置局部钩子
from django.shortcuts import render

from django.http import JsonResponse
from blog.checks import check_name, CheckForm
from blog.models import User

# 定义接口规范
response_dic = {
    'statue': 1,
    'msg': 'ok',
    'data': {}
}


# 注册
def register(request):
    if request.method == "GET":
        return render(request, 'register.html')
    if request.method == "POST":
        # print(request.POST)
        check_form = CheckForm(request.POST)
        if check_form.is_valid():
            # 除了re_password其余都是有用字段
            cleaned_form = check_form.cleaned_data
            cleaned_form.pop('re_password')
            print(cleaned_form)
            # 数据库插入数据
            user = User.objects.create_user(**cleaned_form)
            if user:
                response_dic['statue'] = 1
                response_dic['msg'] = 'ok'
                response_dic['data'] = {}
            else:
                response_dic['statue'] = 2
                response_dic['msg'] = 'error'
                response_dic['data'] = {}
        return JsonResponse(response_dic)
views视图层引用forms策略实现注册功能

2. ajax 请求调用后端数据库查看用户是否存在

# 用户名重复验证
def check_name(username):
    print(username)
    # user = authenticate(username=username)
    user = User.objects.filter(username=username)
    if user:
        return '用户已存在'
    else:
        return 'OK'


#写一个验证用户名的函数
# 校验用户名是否重名
def check_username(request):
    if request.is_ajax():
        username = request.GET.get('username', None)
        msg = check_name(username)
        response_dic['msg'] = msg

        return JsonResponse(response_dic)


#views层调用check_name函数来返回给数据给前端的ajax请求
<script src="/static/bs-3.3.7/js/jquery-3.3.1.js"></script>
<script>
    // 获取焦点事件: 所有.input-div下的input都有该事件
    $('.input-div input').focus(function () {
        $(this).next().text("")
    });


    // 失去焦点事件
    $('#username').blur(function () {
        // 发送用户名重名校验请求
        var username = $(this).val();
        var _this = this
        // @前台先完成前端校验
        if (username) {  // 有内容才校验
            $.ajax({
                url: '/check_username/',
                type: 'get',
                data: {
                    username: username
                },
                success: function (data) {
                    if (data.msg != 'OK') {
                        $(_this).next().text(data.msg)
                    }
                }
            })
        }

    })



    // 失去焦点事件
    $('#password').blur(function () {
        // 发送用户名重名校验请求
        var password = $(this).val();
        var length = password.length;
        if (length < 6) {
            $(this).next().text("密码过短")
        } else if (length > 16) {
            $(this).next().text("密码过长")
        }
    })


    // 表单值变化检测事件
    $('#re_password').on('input', function () {
        password = $('#password').val();
        re_password = $(this).val();
        console.log(password)
        console.log(re_password)
        if (password != re_password) {
            $(this).next().text("密码不相同")
        } else {
            $(this).next().text("")
        }
    })

    // 注册请求
    $('.register').click(function () {

        key_values = $('.form').serializeArray();   //  这里是拿到form表单输入的全部内容信息

        
        form_data = new FormData();
        $.each(key_values, function (index, obj) {
            // console.log(obj.name, obj.value)
            form_data.append(obj.name, obj.value);  // 已经包含了csrftoken
        });

        $.ajax({
            url: "/register/",
            type: 'post',
            data: form_data,
            contentType: false,
            processData: false,
            success: function (data) {
                console.log(data)
            }

        })
        
    })
</script>
前端的ajax逻辑判断

猜你喜欢

转载自www.cnblogs.com/gukai/p/10776160.html