用户注册

1、首先实现一个注册页面

 

用户注册需要用到form主键进行验证

 

views.py

from django.shortcuts import HttpResponse,render,redirect
from django.http import JsonResponse
from django.contrib import auth
from blog.Myforms import UserForm
from blog.models import *




def register(request):
    if request.is_ajax():
        form_ = UserForm(request.POST) #对用户的信息进行过滤
        data = {"user":None,"msg":None}

        if form_.is_valid():  #如果用户注册输入的信息全部符合规定则返回True
            print(form_.cleaned_data)  #所有的干净的信息都在form.cleaned_data中
            data["user"] = form_.cleaned_data.get("user")
            user = form_.cleaned_data.get("user")
            pwd = form_.cleaned_data.get("pwd")
            email = form_.cleaned_data.get("email")
            avatar_obj = request.FILES.get("avatars") #判断用户是否上传头像,没有则设置默认头像
            if avatar_obj:
                user_obj = UserInfo.objects.create_user(username=user,password=pwd,email=email,avatar=avatar_obj)
            else:
                user_obj = UserInfo.objects.create_user(username=user, password=pwd, email=email)
        else:

             #没有通过的错误信息会存放在form.error中
            print(form_.cleaned_data)
            print(form_.errors)
            data["msg"] = form_.errors


        return JsonResponse(data)

    form = UserForm()  #get请求时生成form组件对象,返回给页面,使用模板语法

    return render(request,"register.html",{"form":form})    

  

 

 

创建Myforms.py文件

from django.core.exceptions import  ValidationError
from django import forms
from django.forms import widgets
from blog.models import UserInfo



w1 = widgets.TextInput(attrs={"class":"form-control"},)
w2 = widgets.PasswordInput(attrs={"class":"form-control"},)
w3 = widgets.EmailInput(attrs={"class":"form-control"},)


class UserForm(forms.Form):
    #对输入的用户信息进行过滤
    user = forms.CharField(max_length=32,label="用户名",widget=w1)
    pwd = forms.CharField(max_length=16,label="密码",widget=w2)
    r_pwd = forms.CharField(max_length=16,label="确认密码",widget=w2)
    email = forms.EmailField(label="邮箱",widget=w3)


    def clean_name(self):
     #使用钩子对用户输入信息,进行自定义方法的验证
        user = self.cleaned_data.get("user")
        user_obj = UserInfo.objects.filter(username=user)

        if not user_obj:
            return user
        else:
            raise ValidationError("用户名已注册")

    def clean(self):

        pwd = self.cleaned_data.get("pwd")
        r_pwd = self.cleaned_data.get("r_pwd")

        if pwd and r_pwd:
            if pwd == r_pwd:
                return self.cleaned_data
            else:
                raise ValidationError("两次密码不一致")
        else:
            return self.cleaned_data

  

 

register.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link rel="stylesheet" type="text/css" href="/static/blog/bs/css/bootstrap.css">
    <style type="text/css">

        #avatars {
            width: 60px;
            height: 60px;
            margin-left: 15px;
        }

        #file_up {
            display: none;
        }

        .error {
            color: red;
        }

    </style>

</head>


<body>

<h3>注册页面</h3>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-lg-offset-3">
           
            <form id="form">
    
                {% csrf_token %}
                {% for foo in form %}
                    <div class="form-group">
                        <label for="{{ foo.auto_id }}">{{ foo.label }}</label>
                        {{ foo }}<span class="pull-right error"></span>
                    </div>
                {% endfor %}

                <div class="form-group">

                    <label for="file_up">头像<img src="/media/avatars/default.png" id="avatars" alt="用户头像"></label>
                    <input type="file" id="file_up">

                </div>

                <input type="button" value="submit" class="btn btn-default" id="regBtn">

            </form>

        </div>
    </div>


</div>


</body>


<script src="/static/js/jquery-3.3.1.min.js"></script>

<script type="text/javascript">

    $(function () {
        $("#file_up").change(function () {
            //获取选中头像
            var file_obj = $(this)[0].files[0];
            //获取选中头像的路径
            var reader = new FileReader();
            reader.readAsDataURL(file_obj);
            reader.onload = function () {
                $("#avatars").attr("src", reader.result)
            }

        });
        $("#regBtn").click(function () {
            var requestData = $("#form").serializeArray();
            console.log(requestData);
            var formdata = new FormData();

            $.each(requestData, function (index, ele) {
                console.log(ele.name);
                formdata.append(ele.name, ele.value)
            });
            formdata.append("avatars", $("#file_up")[0].files[0]);

            {#           formdata.append("csrfmiddlewaretoken",$("[name='csrfmiddlewaretoken']").val());#}
            {#            formdata.append("user",$("#id_user").val());#}
            {#            formdata.append("pwd",$("#id_pwd").val());#}
            {#            formdata.append("r_pwd",$("#id_r_pwd").val());#}
            {#            formdata.append("email",$("#id_email").val());#}


            $.ajax({
                url: "",
                type: "post",
                contentType: false,
                processData: false,
                data: formdata,
                success: function (data) {
                    console.log(data);
                    if (data.user) {
                        console.log(123)
                    }
                    else {
                        //清空错误信息
                        $(".error").html("");
                        $(".form-group").removeClass("has-error");
                        $.each(data.msg, function (k, v) {
                            if (k === "__all__") {
                                $("#id_r_pwd").next().html(v).parent().addClass("has-error")
                            }
                            else {
                                $("#id_" + k).next().html(v).parent().addClass("has-error");

                            }

                        })
                    }
                }
            })
        })
    })

</script>


</html>

  

 

posted @ 2018-06-20 08:15  Zhitao  阅读(344)  评论(0编辑  收藏  举报