Django 登陆注册实现

登陆

自定义的form组件

class LoginForm(forms.Form):
    username=forms.CharField(max_length=8, min_length=3, label='用户名', error_messages={
        'max_length': '用户名最长8位',
        'min_length': '用户名最少3位',
        'required': '用户名不能为空',
    }, widget=forms.TextInput(attrs={'class': 'form-control'}))
    password = forms.CharField(max_length=8, min_length=3, label='密码', error_messages={
        'max_length': '密码最长8位',
        'min_length': '密码最少3位',
        'required': '密码不能为空',
    }, widget=forms.PasswordInput(attrs={'class': 'form-control'}))
    def clean_username(self):
        username = self.cleaned_data.get('username')
        user = models.UserInfo.objects.filter(username=username)
        if not user:
            self.add_error('username', '用户名不存在')
        else:
            return username
    def clean(self):
        password = self.cleaned_data.get('password')
        username = self.cleaned_data.get('username')
        user=auth.authenticate(username=username,password=password)
        if not user:
            self.add_error('password','密码错误')
        else:
            return self.cleaned_data

 html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css">
    <script src="/static/bootstrap-3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h2 class="text-center">登陆</h2>
            <hr>
            <form id="my_form">
                {% csrf_token %}
                {% for foo in form_obj %}
                    <div class="form-group">
                        <label for="{{ foo.auto_id }}">{{ foo.label }}</label>
                        {{ foo }}
                        <span class="errors pull-right" style="color: red"></span>
                    </div>
                {% endfor %}
                <div style="margin-top: 50px">
                    <input type="button" style="" class="btn btn-primary pull-right" id="id_button" value="登陆">
                </div>
            </form>
        </div>
    </div>
</div>
<script>
    $('#id_button').click(function () {
        let formData = new FormData();
        $.each($('#my_form').serializeArray(), function (index, obj) {
            formData.append(obj.name, obj.value)
        });
        $.ajax({
            url: '',
            type: 'post',
            data: formData,
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.code == 100) {
                    location.href = data.url
                } else {
                    $.each(data.msg, function (index, obj) {
                        let targetId = '#id_' + index;
                        $(targetId).next().html(obj[0]).parent().addClass('has-error')
                    })
                }
            }
        })
    });
    $('input').focus(function () {
        $(this).next().html('').parent().removeClass('has-error')
    })
</script>
</body>
</html>
View Code

 views视图函数

def login(request):
    response_msg = {'code': 100, 'msg': ''}
    form_obj = myforms.LoginForm()
    if request.method == 'POST':
        form_obj = myforms.LoginForm(request.POST)
        if form_obj.is_valid():
            clean_data = form_obj.cleaned_data
            user = auth.authenticate(**clean_data)
            if user:
                response_msg['msg'] = '登陆成功'
                auth.login(request, user)
                response_msg['url'] = '/home/'
        else:
            response_msg['code'] = 101
            response_msg['msg'] = form_obj.errors
        return JsonResponse(response_msg)
    return render(request, 'login.html', locals()) 

注册

自定义form组件

class RegForm(forms.Form):
    username = forms.CharField(max_length=8, min_length=3, label='用户名', error_messages={
        'max_length': '用户名最长8位',
        'min_length': '用户名最少3位',
        'required': '用户名不能为空',
    }, widget=forms.TextInput(attrs={'class': 'form-control'}))
    password = forms.CharField(max_length=8, min_length=3, label='密码', error_messages={
        'max_length': '密码最长8位',
        'min_length': '密码最少3位',
        'required': '密码不能为空',
    }, widget=forms.PasswordInput(attrs={'class': 'form-control'}))
    confirm_password = forms.CharField(max_length=8, min_length=3, label='确认密码', error_messages={
        'max_length': '确认密码最长8位',
        'min_length': '确认密码最少3位',
        'required': '确认密码不能为空',
    }, widget=forms.PasswordInput(attrs={'class': 'form-control'}))
    email = forms.CharField( label='邮箱', error_messages={
        'invalid': '邮箱格式不正确',
        'required': '密码不能为空',
    }, widget=forms.EmailInput(attrs={'class': 'form-control'}))

    # 局部钩子 校验用户是否已存在
    def clean_username(self):
        username = self.cleaned_data.get('username')
        user = models.UserInfo.objects.filter(username=username)
        if user:
            self.add_error('username', '用户名已存在')
        else:
            return username

    # 全局钩子 校验密码是否一致

    def clean(self):
        password = self.cleaned_data.get('password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if not password == confirm_password:
            self.add_error('confirm_password', '两次密码不一致')
        else:
            return self.cleaned_data

html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css">
    <script src="/static/bootstrap-3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <h2 class="text-center">注册</h2>
            <hr>
            <form id="my_form">
                {% csrf_token %}
                {% for foo in form_obj %}
                    <div class="form-group">
                        <label for="{{ foo.auto_id }}">{{ foo.label }}</label>
                        {{ foo }}
                        <span class="errors pull-right" style="color: red"></span>
                    </div>
                {% endfor %}
                <div class="form-group">
                    <label for="id_my_file">头像
                        <img src="/static/img/default.jpg" alt="" width="80" style="margin-left: 20px" id="id_img">
                    </label>
                    <input type="file" name="my_file" id="id_my_file" style="display: none">
                </div>
                <input type="button" class="btn btn-primary pull-right" id="id_button" value="提交">
            </form>
        </div>
    </div>
</div>
<script>
    $('#id_my_file').change(function () {
        //获取当前用户上传到的文件对象
        let my_file_obj = $(this)[0].files[0];
        //需要用文件阅读器这个内置对象
        let fileReader = new FileReader();
        //将文件对象丢给文件阅读器
        fileReader.readAsDataURL(my_file_obj);
        //将文件对象放入img标签的src属性中
        //当文件对象全部加载完毕再渲染
        fileReader.onload = function () {
            $('#id_img').attr('src', fileReader.result);
        }
    });
    $('#id_button').click(function () {
        let formDate = new FormData();
        //自动获取form表单中所有input框键值对
        $.each($('#my_form').serializeArray(), function (index, obj) {
            formDate.append(obj.name, obj.value)//自动添加了普通的键值对,文件对象需要你手动添加
        });
        //手动添加文件对象
        formDate.append('my_file', $('#id_my_file')[0].files[0]);
        $.ajax({
            url: '',
            type: 'post',
            data: formDate,
            //用formData传数据的时候需要指定两个参数
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.code == 100) {
                    location.href = data.url
                } else {
                    $.each(data.msg, function (index, obj) {
                        //手动拼接处forms组件渲染的input的id值
                        let targetId = '#id_' + index;
                        $(targetId).next().html(obj[0]).parent().addClass('has-error')
                    })
                }
            }

        })
    });
    $('input').focus(function () {
        $(this).next().html('').parent().removeClass('has-error')
    })
</script>
</body>
</html>
View Code

views视图函数

def register(request):
    response_msg = {'code': 100, 'msg': ''}
    form_obj = myforms.RegForm()
    if request.method == "POST":
        form_obj = myforms.RegForm(request.POST)
        if form_obj.is_valid():
            clean_data = form_obj.cleaned_data
            #         删除确认密码的键值对
            clean_data.pop('confirm_password')
            #         获取用户上传的头像
            user_avatar = request.FILES.get('my_file')

            if user_avatar:
                clean_data['avatar'] = user_avatar
            models.UserInfo.objects.create_user(**clean_data)
            response_msg['msg'] = '注册成功'
            response_msg['url'] = '/login/'
        else:
            response_msg['code'] = 101
            response_msg['msg'] = form_obj.errors
        return JsonResponse(response_msg)
    return render(request, 'register.html', locals())

猜你喜欢

转载自www.cnblogs.com/ShenJunHui6/p/10765270.html