Django2.0——实现简易登陆、注册

思路:

实现简易的登陆、注册,我们至少需要三个HTML页面,一个主页面、一个登陆界面、一个注册界面。为了存储和校验用户的账号和密码,我们需要写一个模型类(用于映射到数据库)、两个form类(一个登陆、一个注册,用户校验前端传来的数据是否合法)、视图函数、url配置。出于安全考虑,我们还要将密码进行加密再存储到数据库,这里用的hash加密,django已封装好了这个库,位于django.contrib.auth.hashers中的make_password方法,还有个check_password方法用于检验加密前后的密码是否属于同一个。

模板代码如下:

主页模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>家目录</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }
    </style>
</head>
<body>
你好 {{ username }} <br>
<a href = {% url 'baidu1_login' %} >登陆</a>
<a href = {% url 'baidu1_register' %}>注册</a>
<a href = {% url 'baidu1_loginout' %}>退出</a>

</body>
</html>

注册模板

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
    <style>
        div img{
            display:inline-block;
            width:130px;
            height:80px;
            vertical-align: 0px;
        }
        div p{
            display: inline-block;
            width:130px;
            height:80px;
            margin-left: 10px;
            text-align:center;
            line-height:50px;
            vertical-align:33px;
        }
        input{
            display: inline-block;
            width:300px;
            height:30px;
        }


        .four{
            width:300px;
        }
        .yan{
            width:181px;
            height:36px;
        }
        #o666{
            width:10px;
            height:10px;
        }
        label{
            font-size:12px;
            vertical-align:1px;
        }
        .zhuce{
            display:inline-block;
            margin-left: 55px;
            background-color:blue;
            color:white;
            padding:0px;
            border-width:0px;
            height:46px;
        }

    </style>
</head>
<body>
<div>
    <img src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3572347546,3948256807&fm=27&gp=0.jpg" alt="logo">
    <p>注册百度账号</p>
</div>
    <form action = "" method = "post">
        {% csrf_token %}
        <p>用户名&nbsp;<input type = "text" name = "username" placeholder="请设置用户名" ><span style ="color:red">{{ userform.username.errors.0 }}</span></p>
        <p>密&emsp;码&nbsp;<input type="password" name = "password" placeholder="请设置登陆密码" /><span style ="color:red">{{ userform.password.errors.0 }}</span></p>
        <p>邮&emsp;箱&nbsp;<input type = "text" name = 'email' placeholder="请输入邮箱" class = "four"/>&nbsp;<span style ="color:red">{{ userform.email.errors.0 }}</span>
        <p>
            <input type = "checkbox" id = "o666">
            <label for="o666">阅读并接受《百度用户协议》及《百度隐私权保护声明》</label>
        </p>
        <p>
            <input type = "submit" value = "注册" class = "zhuce">
        </p>

    </form>

</body>
</html>

登陆模板:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登陆</title>
    <style>
        div img{
            display:inline-block;
            width:130px;
            height:80px;
            /*border: solid 5px red;*/
            vertical-align: 0px;
        }
        div p{
            /*border: solid 5px red;*/
            display: inline-block;
            width:130px;
            height:80px;
            margin-left: 10px;
            /*padding-left:20px;*/
            /*padding-top:20px;*/
            text-align:center;
            line-height:50px;
            vertical-align:33px;
            /*vertical-align: super;*/
        }
        input{
            display: inline-block;
            width:300px;
            height:30px;
        }


        .four{
            width:300px;
        }
        .yan{
            width:181px;
            height:36px;
        }
        #o666{
            width:10px;
            height:10px;
        }
        label{
            font-size:12px;
            vertical-align:1px;
        }
        .zhuce{
            display:inline-block;
            margin-left: 55px;
            background-color:blue;
            color:white;
            padding:0px;
            border-width:0px;
            height:46px;
        }

    </style>
</head>
<body>
<div>
    <img src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3572347546,3948256807&fm=27&gp=0.jpg" alt="logo">
    <p>登陆百度账号</p>
</div>
    <form action = "" method = "post">
        {% csrf_token %}
        <p>用户名&nbsp;<input type = "text" name = "username" placeholder="请设置用户名" /></p>
        <p>密&emsp;码&nbsp;<input type="password" name = "password" placeholder="请设置登陆密码" /></p>

        <p>
            <input type = "submit" value = "登陆" class = "zhuce">
        </p>

    </form>

</body>
</html>

app名为baidu,子路由分配如下:

from django.urls import path
from .import views

urlpatterns = [
    path('home/',views.home,name = 'baidu1_home'),
    path('login/',views.login,name = 'baidu1_login'),
    path('register/',views.register,name = 'baidu1_register'),
    path('loginout/',views.loginout,name = "baidu1_loginout"),
]

主路由分配:

path('baidu1/',include('baidu1.urls'))

模型类如下:

from django.db import models

# Create your models here.

class baidu_User(models.Model):
    user_name = models.CharField(max_length=15,null=False,unique=True)
    password = models.CharField(max_length=200)
    email = models.EmailField()

form类如下:

from django import forms

class Register_form(forms.Form):
    username = forms.CharField(required=True,min_length=6,max_length=15,error_messages={
        'min_length':'用户名长度不能低于6',
        'max_length':'用户名长度不能大于15',
        'require':'用户名不能空',
    })
    password = forms.CharField(min_length=6,required=True,error_messages={
        'min_length':'密码长度不能低于6',
        'require':'密码不能空',
    })
    email = forms.EmailField()

class Login_form(forms.Form):
    username = forms.CharField(required=True, min_length=6, max_length=15, error_messages={
        'min_length': '用户名长度不能低于6',
        'max_length': '用户名长度不能大于15',
        'require': '用户名不能空',
    })
    password = forms.CharField(min_length=6, max_length=30, required=True, error_messages={
        'min_length': '密码长度不能低于6',
        'require': '密码不能空',
        })

视图函数如下:

from django.shortcuts import render,redirect,reverse
from django.http import HttpResponse
# -*- coding:utf-8 -*-
# Create your views here.
from .form import Register_form,Login_form
from .models import baidu_User
from django.contrib.auth.hashers import make_password,check_password

def home(request):
    username = request.session.get('username','游客') #默认是游客
    return render(request,'baidu1/home.html',context={
        'username':username,
    })


def login(request):
    if request.method == "GET":
        return render(request,'baidu1/login.html')
    elif request.method == 'POST':
        User_form = Login_form(request.POST)
        if User_form.is_valid():
            username = User_form.cleaned_data.get('username')
            password = User_form.cleaned_data.get('password')
            user = baidu_User.objects.filter(user_name=username)
            if user:
                if (check_password(password,user[0].password)):  #验证密码的正确性
                    request.session['username'] = username    #服务端返回一个sessionid给客户端
                    return render(request,'baidu1/home.html',context={
                        'username':username
                    })
                else:
                    return redirect(reverse('baidu1_login'))
        else:
            return render(request, reverse('baidu1_login'), context={
                'userform': User_form,
            })
    else:
        return HttpResponse("error")

def register(request):
    if request.method == 'GET':
        return render(request,'baidu1/register.html')
    elif request.method == 'POST':
        User_form = Register_form(request.POST)
        if User_form.is_valid():
            username = User_form.cleaned_data.get('username')
            password = User_form.cleaned_data.get('password')
            password = make_password(password)   #密码加密
            email =  User_form.cleaned_data.get('email')
            user  =baidu_User(user_name = username,password = password,email = email)
            user.save()    #保存到数据库
            return HttpResponse("注册成功")
        else:
            return render(request,'baidu1/register.html',context={
               'userform':User_form,
            })
    else:
        return HttpResponse('ERROR')

def loginout(request):
    request.session.flush()   #清除当前会话,即退出当前用户
    return redirect(reverse('baidu1_home'))

效果如下:

点击注册,输入用户名223,密码123,发现界面提示数据不合法。

再次输入合法的数据,即可成功进行注册。

打开数据库,可以发现密码已被加密。

进入登陆界面进行登陆

登陆后界面如下,此时用户名已改变。

打开存储在本地的cookies,发现服务端发来了一个sessionid。

posted @ 2018-12-15 01:04  龙~白  阅读(1127)  评论(0编辑  收藏  举报