bbs 注册功能的搭建

大标 2022年3月16日20:31:20
评论
18

目录

\'\'\'forms校验\'\'\'

from django import forms
from django.forms import widgets
from  blog import  models
from django.core.exceptions import ValidationError
\'\'\'注册校验,写入样式\'\'\'


class RegisterForm(forms.Form):
    # 名称校验
    username = forms.CharField(
        max_length=18, min_length=3,label=\'用户名\',
        error_messages={\'required\': \'该字段必填\', \'max_length\': \'名字过长,不能超过18个字符\',
                        \'min_length\': \'名字过短,不能少于三个字符\'},
        widget=widgets.TextInput(attrs={\'class\': \'form-control\'})
    )
    # 密码校验
    password = forms.CharField(
        max_length=18, min_length=3,label=\'密码\',
        error_messages={\'required\': \'该字段必填\', \'max_length\': \'密码过长,不能超过18个字符\',
                        \'min_length\': \'密码过短,不能少于三个字符\'},
        widget=widgets.PasswordInput(attrs={\'class\': \'form-control\'})
    )
    re_password = forms.CharField(
        max_length=18, min_length=3,label=\'确认密码\',
        error_messages={\'required\': \'该字段必填\', \'max_length\': \'密码过长,不能超过18个字符\',
                        \'min_length\': \'密码过短,不能少于三个字符\'},
        widget=widgets.PasswordInput(attrs={\'class\': \'form-control\'})
    )

    # 邮箱
    email = forms.EmailField(
        error_messages={\'required\': \'该字段必填\', \'invalid\': \'邮箱格式不正确\'},label=\'邮箱\',
        widget=widgets.EmailInput(attrs={\'class\': \'form-control\'})
    )

    # 局部钩子,校验用户是否存在
    def clean_username(self):
        username = self.cleaned_data.get(\'username\')
        # 拿到数据判断用户在不在表中
        user = models.UserInfo.objects.filter(username=username).first()
        if user:
            # 用户存在抛异常
            raise ValidationError(\'该用户以存在\')
        else:
            return username

    # 全局钩子,校验密码是否一致
    def clean(self):
        password = self.cleaned_data.get(\'password\')
        re_password = self.cleaned_data.get(\'re_password\')
        if not password == re_password:
            raise ValidationError(\'两次密码不一致\')
{#注册功能前端功能的设置#}
    {## 发送ajax请求,使用的Formdata#}
    {##form标签.serializeArray()#}
    {##}
    {## 整体代码#}
    $(\'#id_submit\').click(function () {
        let formdata = new FormData()
        formdata.append(\'myfile\', $(\'#myfile\')[0].files[0])
        //方案一
        /*
        formdata.append(\'username\',$(\'#id_username\').val())
        formdata.append(\'password\',$(\'#password\').val())
        formdata.append(\'re_password\',$(\'#id_re_password\').val())
        formdata.append(\'email\',$(\'#id_email\').val())
         */

        //方案二
        {#serializeArray()    将myfile 里面的数据转换成列表的形式#}
        let form_data = $(\'#my_form\').serializeArray()
        //console.log(form_data)
        {#each循环取值#}
        $.each(form_data, function (index, element) {
            //console.log(index)
            //console.log(element)
            formdata.append(element.name, element.value)
        })
        //console.log(formdata.get(\'username\'))
        $.ajax({
            url: \'/register/\',
            method: \'post\',
            contentType: false,
            processData: false,
            data: formdata,
            success: function (data) {
                console.log(data)
                {#跳转到前端页面#}
                if (data.status == 100) {
                    location.href = data.next_url
                    //location.href=\'/login/\'
                } else {
                    {#each循环#}
                    $.each(data.msg, function (key, value) {
                        //console.log(\'#id_\'+key)
                        if (key == \'__all__\') {
                            //全局钩子抛出的错
                            $(\'#id_error\').html(value[0])
                        } else {
                            //取到input标签的下一个
                            //$(\'#id_\'+key).next().html(value[0])
                            //链式调用
                            //$(\'#id_\'+key).parent().addClass(\'has-error\')
                            //链式调用
                            //局部错误
                            //先取到input框 然后取到input框下面的标签在下面的标签上将操作信息写进来  然后找了一个复空签加了has_error
                            $(\'#id_\' + key).next().html(value[0]).parent().addClass(\'has-error\')

                        }

                    })

                    //加了一个定时器,3s以后干某些事
                    setTimeout(function () {
                        //清除红色框
                        $(\'.form-group\').removeClass(\'has-error\')
                        //清空所有错误信息
                        $(\'.error\').html(\'\')
                    }, 3000)
                }


            }
        })


    })

 

view.py

from django.shortcuts import render,HttpResponse,redirect
from blog import models
# Create your views here.
from blog.blog_forms import RegisterForm
from django import forms
from django.http import JsonResponse


# 数据校验
def register(request):
    if request.method==\'GET\':
        register_form=RegisterForm()
        return render(request,\'register.html\',context={\'form\':register_form})
    elif request.method ==\'POST\':
        response = {\'status\': 100, \'msg\':None}
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            # 数据校验通过
            # 可能传头像   可能没有传头像
            # models.UserInfo.objects.create_user()
            clean_data=register_form.cleaned_data
            print(clean_data)
            my_file =request.FILES.get(\'myfile\')
            if my_file:#上传了头想
            #filefiled字段类型直接接受一个文件对象
            #它会把文件存到upload_to=\'avatar\'/,然后把路径存到数据库中
            # 相当于with open 打开文件,把文件存到avatar路径下 然后把路径赋值给avatar这个字段
                clean_data[\'avatar\'] = my_file
            clean_data.pop(\'re_password\')
            models.UserInfo.objects.create_user(**clean_data)
            response[\'msg\'] = \'注册成功\'
            # 注册成功跳转到登录页面
            response[\'next_url\'] = \'/login/\'

        else:
            response[\'status\'] = 101
            response[\'msg\'] = register_form.errors

        return JsonResponse(response)

 

success: function (data) {
                console.log(data)
                {#跳转到前端页面#}
                if (data.status == 100) {
                    location.href = data.next_url
                    //location.href=\'/login/\'
                } else {
                    {#each循环#}
                    $.each(data.msg, function (key, value) {
                        //console.log(\'#id_\'+key)
                        if (key == \'__all__\') {
                            //全局钩子抛出的错
                            $(\'#id_error\').html(value[0])
                        } else {
                            //取到input标签的下一个
                            //$(\'#id_\'+key).next().html(value[0])
                            //链式调用
                            //$(\'#id_\'+key).parent().addClass(\'has-error\')
                            //链式调用
                            //局部错误
                            //先取到input框 然后取到input框下面的标签在下面的标签上将操作信息写进来  然后找了一个复空签加了has_error
                            $(\'#id_\' + key).next().html(value[0]).parent().addClass(\'has-error\')

                        }

                    })

                    //加了一个定时器,3s以后干某些事
                    setTimeout(function () {
                        //清除红色框
                        $(\'.form-group\').removeClass(\'has-error\')
                        //清空所有错误信息
                        $(\'.error\').html(\'\')
                    }, 3000)
                }


            }
        })

 

  • 我的微信
  • 微信扫一扫
  • weinxin
  • 我的微信公众号
  • 微信扫一扫
  • weinxin
大标
  • 本文由 发表于 2022年3月16日20:31:20
  • 转载请务必保留本文链接:https://www.tanhuibiao.com/script/qita/5149.html
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: