博客系统-登录注册

url配置

from django.conf.urls import url,include
from django.contrib import admin
from blogCMS import settings
from django.views.static import serve

from blog import views
from blog import urls
urlpatterns = [
    url(r'^login/', views.login),
    url(r'^log_out/', views.log_out),
    url(r'^reg/', views.reg),
]

 

登录相关

视图

def login(request):
    if request.method=="POST":
        print("====可以走过来")
        username = request.POST.get("username")
        password = request.POST.get("password")
        validCode = request.POST.get("valid_code")

        login_response = {"is_login": False, "error_msg": None}

        if validCode.upper()==request.session.get("keepValidCode").upper():          #验证码不区分大小写
            user = auth.authenticate(username=username,password=password)
            if user:
                login_response["is_login"]=True      #验证通过
                auth.login(request,user)

                # request.session["username"] = username
            else:
                login_response["error_msg"]="用户名或密码错误"   #验证不通过
        else:
            login_response["error_msg"]="验证码输入有误"         #验证码错误
        import json
        return HttpResponse(json.dumps(login_response))
    else:
        # print(request.session["keepValidCode"])
        return render(request,"login.html")

前端HTML

{#DOCTYPE html>#}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Titletitle>
    <script src="/static/jquery/jquery-3.2.1.min.js">script>

    <script src="/static/jquery/jquery.session.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>
    
    <script src="http://code.jquery.com/jquery-1.12.3.min.js">script>
    
    <script src="http://static.geetest.com/static/tools/gt.js">script>
head>
<style>style>
<body>

<div class="container" style="margin-top: 100px">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <div class="panel panel-primary">
                <div class="panel-heading">
                    <h2>欢迎登录h2>
                div>
                <div class="panel-body">
                    <form class="form-signin" novalidate>
                        {% csrf_token %}
                        <div class="form-group">
                            <label for="username">用户名label>
                            <input type="text" id="username" class="form-control" placeholder="请输入用户名" required
                                   autofocus>
                        div>
                        <div class="form-group">
                            <label for="password">密码label>
                            <input type="password" id="password" class="form-control" placeholder="请输入密码" required
                                   autofocus>
                        div>

                        <div class="row valiCode">

                            <div class="col-md-5">
                                <div class="form-group">
                                    <label for="validCode">验证码label>
                                    <input type="text" class="form-control validCode_text" id="validCode"
                                           placeholder="请输入右侧验证码">
                                div>
                            div>
                            <div class="col-md-7 ">
{#                                <a href="">#}
{#                                    <img class="validCode_img" src="/get_validCode_img/" alt="" width="160px" height="40px" >点击更换验证码#}
{#                                a>#}

                                    <img class="validCode_img" src="/get_validCode_img/" alt="" width="160px" height="40px" title="点击更换验证码">

                                    <div id="popup-captcha">div>

                                <input type="button" class="ret" style="background: none;border: none" id="fresh" value="看不清,换一张">
                            div>

                        div>

                        <div class="checkbox">
                            <label>
                                <input type="checkbox" value="remember-me"> 记住密码
                            label>

                            <a href="">忘记密码a>
                        div>
                    form>
                    <div class="col-md-4">
                        <button class="btn  btn-info btn-block" id="subBtn">登录button>
                        <span class="error">span>
                    div>
                    <div class="col-md-4">
                        <button class="btn  btn-success btn-block" id="register">注册button>
                    div>
                div>
            div>
        div>
    div>
div>





<script src="/static/jquery/jquery.cookie.js">script>
<script src="/static/blog/login.js">script>
<script>


    var handlerPopup = function (captchaObj) {
        // 成功的回调
        captchaObj.onSuccess(function () {
            var validate = captchaObj.getValidate();
            $.ajax({
                url: "/pc-geetest/ajax_validate", // 进行二次验证
                type: "post",
                dataType: "json",
                data: {
                    username: $('#username').val(),
                    password: $('#password').val(),
                    csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val(),
                    geetest_challenge: validate.geetest_challenge,
                    geetest_validate: validate.geetest_validate,
                    geetest_seccode: validate.geetest_seccode
                },
                success: function (data) {
                    var response = data;

                    if (response["is_login"]){
                        if ($.cookie("next_path")){
                        location.href=$.cookie("next_path");
                        alert($.cookie("next_path"))
                            $.removeCookie("next_path","",{ expires: -1 })
                        }
                        else{
                            location.href="/index/"
                        }
                    }else{
                        $(".error").html(response["error_msg"]).css("color","red");
                    }
                }
            });
        });
        $("#subBtn").click(function () {
            captchaObj.show();

        });
        // 将验证码加到id为captcha的元素里
        captchaObj.appendTo("#popup-captcha");
        // 更多接口参考:http://www.geetest.com/install/sections/idx-client-sdk.html
    };
    // 验证开始需要向网站主后台获取id,challenge,success(是否启用failback)
    $.ajax({
        url: "/pc-geetest/register?t=" + (new Date()).getTime(), // 加随机数防止缓存
        type: "get",
        dataType: "json",
        success: function (data) {
            // 使用initGeetest接口
            // 参数1:配置参数
            // 参数2:回调,回调的第一个参数验证码对象,之后可以使用它做appendTo之类的事件
            initGeetest({
                gt: data.gt,
                challenge: data.challenge,
                product: "popup", // 产品形式,包括:float,embed,popup。注意只对PC版验证码有效
                offline: !data.success // 表示用户后台检测极验服务器是否宕机,一般不需要关注
                // 更多配置参数请参见:http://www.geetest.com/install/sections/idx-client-sdk.html#config
            }, handlerPopup);
        }
    });

script>


body>
html>

JS

$("#register").click(function () {
        location.href="/reg/"
    });


//     //url无刷新验证码
    $(".validCode_img").click(function () {
        this.src+="?";
    });
//

 

注册相关

视图配置

# 注册
def reg(request):
    if request.method == "POST":
        print(request.FILES)
        regform = RegForm(request,request.POST,request.FILES)
        # print("=====这里是regform=====")

        reg_response = {"user":None,"valid_code":False,"errors":""}
        # print(regform.cleaned_data.get("username"))
        if regform.is_valid():
            print("===this is ===")
            username = regform.cleaned_data.get("username")
            password = regform.cleaned_data.get("password")

            obj = models.UserInfo.objects.create_user(username=username,password=password,avatar=request.FILES.get("img","/avatar/default.png"))
            reg_response["user"]=username
            print("======", reg_response["user"])
        else:
            print("===验证不通过====")
            reg_response["errors"]=regform.errors

        # return HttpResponse("OK")
        return HttpResponse(json.dumps(reg_response))

    regform = RegForm(request)
    return render(request,"reg.html",{"regform":regform})

HTML相关

{#DOCTYPE html>#}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <script src="/static/jquery/jquery-3.2.1.min.js">script>
    <script src="/static/jquery/jquery.cookie.js">script>
    <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css">
head>
<style>

    .cc {
        margin-top: 10px;
    }
    .avator_div {
        position: relative;
        width: 60px;
        height: 60px;
        cursor: hand;
    }
    .avator_img, .avator_file {
        position: absolute;
        left: 80px;
        top: 0;
        width: 60px;
        height: 60px;
    {#        cursor: hand;#}

    }

    .avator_file {
        opacity: 0;
    {#        cursor: hand;#}{#        display: none;#}
    }


style>
<body>


{#<img src="/static/img/top.png" style="width: 100%;position: fixed;top: 0;left: 0;">#}

<div class="container" style="margin-top: 20px">
    <div class="row">
        <h2>注册页面h2>
        <hr>
        <div class="col-md-6">
            <form novalidate>
                {% csrf_token %}
                <div class="cc">用户名:
                    {{ regform.username }}
                div>

                <div class="cc">密码:
                    {{ regform.password }}
                div>

                <div class="cc">确认密码:
                    {{ regform.repassword }}
                div>

                <div class="cc">邮箱:
                    {{ regform.email }}
                div>

                <div class="avator_div cc">
                    <label for="avator">头像:label>
                    <img src="/static/img/default.png" class="avator_img" id="preScan">
                    <input type="file" id="avator" class="avator_file">
                div>


                <div class="row valiCode">
                    <div class="col-md-5">
                        <div class="form-group">
                            <label for="validCode">验证码:label>
                            {{ regform.valid_code }}
                        div>
                    div>
                    <div class="col-md-7 " style="margin-top: 20px">
                        <img class="validCode_img" src="/get_validCode_img/" alt="" width="160px" height="40px" >
                    div>

                div>

                <button type="button" class="btn btn-success ajax_signUp">点击注册button>


            form>
        div>
        <div class="col-md-4 col-md-offset-1">
            <img src="/static/img/registersideimg.png" alt="">
        div>

    div>
div>


body>

<script src="/static/blog/register.js">script>

<script>


script>


html>

js

// 注册页面的主要js代码


    var per_error_arr = [];

    $(".ajax_signUp").click(function () {
        var form = new FormData();
        form.append("username",$("[name=username]").val());
        form.append("password",$("[name=password]").val());
        form.append("repassword",$("[name=repassword]").val());
        form.append("email",$("[name=email]").val());
        form.append("valid_code",$("[name=valid_code]").val());
        var fileobj =$("#preScan").next()[0].files[0];

        // console.log(fileobj);

        $.ajax({
            url: "/reg/",
            type: "POST",
            data: form,
            processData: false,
            contentType: false,
            headers: {"X-CSRFToken": $.cookie('csrftoken')},
            success: function (data) {

                data = JSON.parse(data);
                if (data["user"]) {
                    alert("OK");
                    location.href="/login/"
                }
                else if(data["errors"]){
                    var error_list = data["errors"];
                    console.log("per_error_arr",per_error_arr);
                    $(".Mr_zhang").css("border","").next().remove();

                    for (var error in error_list){
                        $div=$("<div>").addClass("row");

                       $div_in=$("<div>").addClass("col-md-5").addClass("col-md-offset-9");

                       $div.append($div_in);

                       console.log($div);
                       if (error=="__all__"){
                            $div_in.text("密码不一致!");
                            $("#id_repeat_password").css("border","2px solid red").after($div);
                       }

                       $div_in.text(errors[error]);
                       $("#id_"+error).css("border","2px solid red").addClass("Mr_zhang").after($div);
                    }
                    pre_error_arr=errors_list;
                   console.log("pre_error_arr",pre_error_arr)
                }
            }
        })

    });



    $(".validCode_img").click(function () {
        this.src+="?";
    });


    $("#avator").change(function () {
        console.log("OK");
        var first_file = $(this)[0].files[0];
        var reader = new FileReader();
        reader.readAsDataURL(first_file);
        reader.οnlοad=function () {
            $("#preScan").attr("src",this.result)
        }
    })

*注销

# 注销
def log_out(request):
    auth.logout(request)
    return redirect("/login/")

 

转载于:https://www.cnblogs.com/52-qq/p/8669194.html

你可能感兴趣的:(json,python,javascript)