Django+xadmin 打造线上教育平台


一、完成用户注册和登录功能

 1-1、完成首页页面,访问:http://127.0.0.1:8000/index/

1)html页面代码:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" >
    <title>课程机构列表 - 慕学在线网</title>
    <link rel="stylesheet" type="text/css" href="/static/css/reset.css">
    <link rel="stylesheet" type="text/css" href="/static/css/animate.css">
    <link rel="stylesheet" type="text/css" href="/static/css/style.css">
    
    <script src="/static/js/jquery.min.js" type="text/javascript"></script>
    <script src="/static/js/jquery-migrate-1.2.1.min.js" type="text/javascript"></script>

</head>
<body>
<section class="headerwrap ">
    <header>
        <div  class=" header">
             <div class="top">
                <div class="wp">
                    <div class="fl"><p>服务电话:<b>33333333</b></p></div>
                    <!--登录后跳转-->

                        
                        <!-- <a style="color:white" class="fr registerbtn" href="register.html">注册</a> -->
                        <!-- <a style="color:white" class="fr loginbtn" href="login.html">登录</a>  -->
                        
                        <div class="personal">
                            <dl class="user fr">
                                <dd>bobby<img class="down fr" src="/static/images/top_down.png"/></dd>
                                <dt><img width="20" height="20" src="/static/media/image/2016/12/default_big_14.png"/></dt>
                            </dl>
                            <div class="userdetail">
                                <dl>
                                    <dt><img width="80" height="80" src="/static/media/image/2016/12/default_big_14.png"/></dt>
                                    <dd>
                                        <h2>django</h2>
                                        <p>bobby</p>
                                    </dd>
                                </dl>
                                <div class="btn">
                                    <a class="personcenter fl" href="usercenter-info.html">进入个人中心</a>
                                    <a class="fr" href="/logout/">退出</a>
                                </div>
                            </div>
                        </div>


                </div>
            </div>
{#            header部分#}
            <div class="middle">
                <div class="wp">
                    <a href="/index/"><img class="fl" src="/static/images/logo.jpg"/></a>
                    <div class="searchbox fr">
                        <div class="selectContainer fl">
                            <span class="selectOption" id="jsSelectOption" data-value="course">
                                公开课
                            </span>
                            <ul class="selectMenu" id="jsSelectMenu">
                                <li data-value="course">公开课</li>
                                <li data-value="org">课程机构</li>
                                <li data-value="teacher">授课老师</li>
                            </ul>
                        </div>
                        <input id="search_keywords" class="fl" type="text" value="" placeholder="请输入搜索内容"/>
                        <img class="search_btn fr" id="jsSearchBtn" src="/static/images/search_btn.png"/>
                    </div>
                </div>
            </div>
            
            
            <nav>
                <div class="nav">
                    <div class="wp">
                        <ul>
                            <li class="active" ><a href="index.html">首页</a></li>
                            <li >
                                <a href="course-list.html">
                                    公开课<img class="hot" src="/static/images/nav_hot.png">
                                </a>
                            </li>
                            <li >
                                <a href="teachers-list.html">授课教师</a>
                            </li>
                            <li ><a href="org-list.html">授课机构</a></li>
                        </ul>
                    </div>
                </div>
            </nav>
            
            </div>
    </header>
</section>
<!--crumbs start-->


{#    轮播图#}
    <div class="banner">
            <div class="wp">
                <div class="fl">
                    <div class="imgslide">
                        <ul class="imgs">
                            
                            <li>
                                    <a href="http://www.imooc.com">
                                        <img width="1200" height="478" src="/static/media/banner/2016/11/57a801860001c34b12000460.jpg" />
                                    </a>
                                </li>
                            
                            <li>
                                    <a href="http://www.projectsedu.com">
                                        <img width="1200" height="478" src="/static/media/banner/2016/11/57aa86a0000145c512000460.jpg" />
                                    </a>
                                </li>
                            
                            <li>
                                    <a href="http://www.projectsedu.com">
                                        <img width="1200" height="478" src="/static/media/banner/2016/11/57a801860001c34b12000460_z4Vb8zl.jpg" />
                                    </a>
                                </li>
                            
                            <li>
                                    <a href="http://www.projectsedu.com">
                                        <img width="1200" height="478" src="/static/media/banner/2016/11/57aa86a0000145c512000460_nMwvoQD.jpg" />
                                    </a>
                                </li>
                            
                            <li>
                                    <a href="http://www.projectsedu.com">
                                        <img width="1200" height="478" src="/static/media/banner/2016/11/57aa86a0000145c512000460_GXIBATC.jpg" />
                                    </a>
                                </li>
                            

                        </ul>
                    </div>
                    <div class="unslider-arrow prev"></div>
                    <div class="unslider-arrow next"></div>
                </div>

                </div>


            </div>
<!--banner end-->
<!--feature start-->
    <section>
        <div class="wp">
            <ul class="feature">
                <li class="feature1">
                    <img class="pic" src="/static/images/feature1.png"/>
                    <p class="center">专业权威</p>
                </li>
                <li class="feature2">
                    <img class="pic" src="/static/images/feature2.png"/>
                    <p class="center">课程最新</p>
                </li>
                <li class="feature3">
                    <img class="pic" src="/static/images/feature3.png"/>
                    <p class="center">名师授课</p>
                </li>
                <li class="feature4">
                    <img class="pic" src="/static/images/feature4.png"/>
                    <p class="center">数据真实</p>
                </li>
            </ul>
        </div>
    </section>
<!--feature end-->
<!--module1 start-->
    <section>
        <div class="module">
            <div class="wp">
                <h1>公开课程</h1>
                <div class="module1 eachmod">
                    <div class="module1_1 left">
                        <img width="228" height="614" src="/static/images/module1_1.jpg"/>
                        <p class="fisrt_word">名师授课<br/>专业权威</p>
                        <a class="more" href="course-list.html">查看更多课程 ></a>
                    </div>
                    <div class="right group_list">
                        <div class="module1_2 box">
                            <div class="imgslide2">
                                <ul class="imgs">
                                    
                                    <li>
                                        <a href="course-detail.html">
                                            <img width="470" height="300" src="/static/media/courses/2016/12/python文件处理.jpg" />
                                        </a>
                                    </li>
                                    
                                    <li>
                                        <a href="course-detail.html">
                                            <img width="470" height="300" src="/static/media/courses/2016/12/python面向对象.jpg" />
                                        </a>
                                    </li>
                                    
                                </ul>
                            </div>
                            <div class="unslider-arrow2 prev"></div>
                            <div class="unslider-arrow2 next"></div>
                        </div>
                            
                            <div class="module1_3 box">
                                <a href="course-detail.html">
                                    <img width="233" height="190" src="/static/media/courses/2016/11/mysql.jpg"/>
                                </a>
                                <div class="des">
                                    <a href="course-detail.html">
                                        <h2 title="django入门">django入门</h2>
                                    </a>
                                    <span class="fl">难度:<i class="key">初级</i></span>
                                    <span class="fr">学习人数:3</span>
                                </div>
                                <div class="bottom">
                                    <span class="fl" title="慕课网">慕课网</span>
                                    <span class="star fr">0</span>
                                </div>
                            </div>
                            
                            <div class="module1_4 box">
                                <a href="course-detail.html">
                                    <img width="233" height="190" src="/static/media/courses/2016/11/57035ff200014b8a06000338-240-135.jpg"/>
                                </a>
                                <div class="des">
                                    <a href="course-detail.html">
                                        <h2 title="java入门">java入门</h2>
                                    </a>
                                    <span class="fl">难度:<i class="key">中级</i></span>
                                    <span class="fr">学习人数:0</span>
                                </div>
                                <div class="bottom">
                                    <span class="fl" title="北京大学">北京大学</span>
                                    <span class="star fr">0</span>
                                </div>
                            </div>
                            
                            <div class="module1_5 box">
                                <a href="course-detail.html">
                                    <img width="233" height="190" src="/static/media/courses/2016/11/540e57300001d6d906000338-240-135.jpg"/>
                                </a>
                                <div class="des">
                                    <a href="course-detail.html">
                                        <h2 title="python入门">python入门</h2>
                                    </a>
                                    <span class="fl">难度:<i class="key">中级</i></span>
                                    <span class="fr">学习人数:0</span>
                                </div>
                                <div class="bottom">
                                    <span class="fl" title="南京大学">南京大学</span>
                                    <span class="star fr">0</span>
                                </div>
                            </div>
                            
                            <div class="module1_6 box">
                                <a href="course-detail.html">
                                    <img width="233" height="190" src="/static/media/courses/2016/11/57035ff200014b8a06000338-240-135_dHfj8Nq.jpg"/>
                                </a>
                                <div class="des">
                                    <a href="course-detail.html">
                                        <h2 title="java入门2">java入门2</h2>
                                    </a>
                                    <span class="fl">难度:<i class="key">高级</i></span>
                                    <span class="fr">学习人数:0</span>
                                </div>
                                <div class="bottom">
                                    <span class="fl" title="慕课网2">慕课网2</span>
                                    <span class="star fr">0</span>
                                </div>
                            </div>
                            
                            <div class="module1_7 box">
                                <a href="course-detail.html">
                                    <img width="233" height="190" src="/static/media/courses/2016/11/57035ff200014b8a06000338-240-135_0nFiBSI.jpg"/>
                                </a>
                                <div class="des">
                                    <a href="course-detail.html">
                                        <h2 title="java入门3">java入门3</h2>
                                    </a>
                                    <span class="fl">难度:<i class="key">初级</i></span>
                                    <span class="fr">学习人数:1</span>
                                </div>
                                <div class="bottom">
                                    <span class="fl" title="慕课网3">慕课网3</span>
                                    <span class="star fr">0</span>
                                </div>
                            </div>
                            
                            <div class="module1_8 box">
                                <a href="course-detail.html">
                                    <img width="233" height="190" src="/static/media/courses/2016/11/540e57300001d6d906000338-240-135_MSIqfvw.jpg"/>
                                </a>
                                <div class="des">
                                    <a href="course-detail.html">
                                        <h2 title="python入门2">python入门2</h2>
                                    </a>
                                    <span class="fl">难度:<i class="key">中级</i></span>
                                    <span class="fr">学习人数:0</span>
                                </div>
                                <div class="bottom">
                                    <span class="fl" title="慕课网666">慕课网666</span>
                                    <span class="star fr">0</span>
                                </div>
                            </div>
                            
                    </div>
                </div>
            </div>
        </div>
    </section>
    <section>
        <div class="module greybg">
            <div class="wp">
                <h1>课程机构</h1>
                <div class="module3 eachmod">
                    <div class="module3_1 left">
                        <img width="228" height="463" src="/static/images/module3_1.jpg"/>
                        <p class="fisrt_word">名校来袭<br/>权威认证</p>
                        <a class="more" href="org-list.html">查看更多机构 ></a>
                    </div>
                    <div class="right">
                        <ul>
                            
                                <li class="">
                                    <a href="org-detail-homepage.html">
                                        <div class="company">
                                            <img width="184" height="100" src="/static/media/org/2016/11/imooc.png"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>全国知名</h2>
                                                </div>
                                            </div>
                                        </div>
                                        <p><span class="key" title="慕课网">慕课网</span></p>
                                    </a>
                                </li>
                            
                                <li class="">
                                    <a href="org-detail-homepage.html">
                                        <div class="company">
                                            <img width="184" height="100" src="/static/media/org/2016/11/bjdx.jpg"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>全国知名</h2>
                                                </div>
                                            </div>
                                        </div>
                                        <p><span class="key" title="北京大学">北京大学</span></p>
                                    </a>
                                </li>
                            
                                <li class="">
                                    <a href="org-detail-homepage.html">
                                        <div class="company">
                                            <img width="184" height="100" src="/static/media/org/2016/11/qhdx-logo.png"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>全国知名</h2>
                                                </div>
                                            </div>
                                        </div>
                                        <p><span class="key" title="清华大学">清华大学</span></p>
                                    </a>
                                </li>
                            
                                <li class="">
                                    <a href="org-detail-homepage.html">
                                        <div class="company">
                                            <img width="184" height="100" src="/static/media/org/2016/11/njdx.jpg"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>全国知名</h2>
                                                </div>
                                            </div>
                                        </div>
                                        <p><span class="key" title="南京大学">南京大学</span></p>
                                    </a>
                                </li>
                            
                                <li class="five">
                                    <a href="org-detail-homepage.html">
                                        <div class="company">
                                            <img width="184" height="100" src="/static/media/org/2016/11/imooc_klgAUn5.png"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>全国知名</h2>
                                                </div>
                                            </div>
                                        </div>
                                        <p><span class="key" title="慕课网2">慕课网2</span></p>
                                    </a>
                                </li>
                            
                                <li class="">
                                    <a href="org-detail-homepage.html">
                                        <div class="company">
                                            <img width="184" height="100" src="/static/media/org/2016/11/imooc_Gn1sRjp.png"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>全国知名</h2>
                                                </div>
                                            </div>
                                        </div>
                                        <p><span class="key" title="慕课网3">慕课网3</span></p>
                                    </a>
                                </li>
                            
                                <li class="">
                                    <a href="org-detail-homepage.html">
                                        <div class="company">
                                            <img width="184" height="100" src="/static/media/org/2016/11/imooc_Y2Tonsq.png"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>全国知名</h2>
                                                </div>
                                            </div>
                                        </div>
                                        <p><span class="key" title="慕课网3">慕课网3</span></p>
                                    </a>
                                </li>
                            
                                <li class="">
                                    <a href="org-detail-homepage.html">
                                        <div class="company">
                                            <img width="184" height="100" src="/static/media/org/2016/11/imooc_OO2ykYP.png"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>全国知名</h2>
                                                </div>
                                            </div>
                                        </div>
                                        <p><span class="key" title="慕课网4">慕课网4</span></p>
                                    </a>
                                </li>
                            
                                <li class="">
                                    <a href="org-detail-homepage.html">
                                        <div class="company">
                                            <img width="184" height="100" src="/static/media/org/2016/11/imooc_V0TJOyb.png"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>全国知名</h2>
                                                </div>
                                            </div>
                                        </div>
                                        <p><span class="key" title="慕课网5">慕课网5</span></p>
                                    </a>
                                </li>
                            
                                <li class="five">
                                    <a href="org-detail-homepage.html">
                                        <div class="company">
                                            <img width="184" height="100" src="/static/media/org/2016/11/imooc_qEaMov1.png"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>全国知名</h2>
                                                </div>
                                            </div>
                                        </div>
                                        <p><span class="key" title="慕课网666">慕课网666</span></p>
                                    </a>
                                </li>
                            
                                <li class="">
                                    <a href="org-detail-homepage.html">
                                        <div class="company">
                                            <img width="184" height="100" src="/static/media/org/2016/12/bjdx.jpg"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>全国知名</h2>
                                                </div>
                                            </div>
                                        </div>
                                        <p><span class="key" title="慕学网">慕学网</span></p>
                                    </a>
                                </li>
                            
                                <li class="">
                                    <a href="org-detail-homepage.html">
                                        <div class="company">
                                            <img width="184" height="100" src="/static/media/org/2016/12/imooc_Gn1sRjp.png"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>全国知名</h2>
                                                </div>
                                            </div>
                                        </div>
                                        <p><span class="key" title="python培训机构">python培训机构</span></p>
                                    </a>
                                </li>
                            
                                <li class="">
                                    <a href="org-detail-homepage.html">
                                        <div class="company">
                                            <img width="184" height="100" src="/static/media/org/2016/12/bjdx_cCpdUw8.jpg"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>全国知名</h2>
                                                </div>
                                            </div>
                                        </div>
                                        <p><span class="key" title="vuejs培训">vuejs培训</span></p>
                                    </a>
                                </li>
                            
                                <li class="">
                                    <a href="org-detail-homepage.html">
                                        <div class="company">
                                            <img width="184" height="100" src="/static/media/org/2016/12/imooc_klgAUn5.png"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>全国知名</h2>
                                                </div>
                                            </div>
                                        </div>
                                        <p><span class="key" title="nodejs培训">nodejs培训</span></p>
                                    </a>
                                </li>
                            
                                <li class="five">
                                    <a href="org-detail-homepage.html">
                                        <div class="company">
                                            <img width="184" height="100" src="/static/media/org/2016/12/bjdx_bcd0m07.jpg"/>
                                            <div class="score">
                                                <div class="circle">
                                                    <h2>全国知名</h2>
                                                </div>
                                            </div>
                                        </div>
                                        <p><span class="key" title="慕学在线">慕学在线</span></p>
                                    </a>
                                </li>
                            
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </section>

<footer>
        <div class="footer">
            <div class="wp">
                <ul class="cont">
                    <li class="logo"><a href=""><img src="/static/images/footlogo.png"/></a></li>
                    <li class="code"><img src="/static/images/code.jpg"/><p class="center">扫描关注微信</p></li>
                    <li class="third"><img class="fl" src="/static/images/tell.png"/><p class="tell">33333333</p><p class="time">周一至周日 9:00-18:00</p></li>
                </ul>

            </div>
            <p class="line"></p>
            <div class="wp clear">
                <span class="fl">? 2016 www.projectsedu.com 慕学在线-在线学习交流平台 保留所有权利</span>
                <span class="fr">copyright ? 2016 ICP备案证书号:蜀ICP备xxxxx号-1</span>
            </div>
        </div>
    </footer>

<section>
    <ul class="sidebar">
        <li class="qq">
            <a target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin=2023525077&site=qq&menu=yes"></a>
        </li>
        <li class="totop"></li>
    </ul>
</section>
<script src="/static/js/selectUi.js" type='text/javascript'></script>
<script src="/static/js/deco-common.js" type='text/javascript'></script>
<script type="text/javascript" src="/static/js/plugins/laydate/laydate.js"></script>
<script src="/static/js/plugins/layer/layer.js"></script>
<script src="/static/js/plugins/queryCity/js/public.js" type="text/javascript"></script>
<script src="/static/js/unslider.js" type="text/javascript"></script>
<script src="/static/js/plugins/jquery.scrollLoading.js"  type="text/javascript"></script>
<script src="/static/js/deco-common.js"  type="text/javascript"></script>

    <script type="text/javascript" src="/static/js/index.js"></script>

</body>
</html>
View Code 

依赖项目中的静态文件:

 

2)在users/views.py中编写关于首页访问的代码:

from django.shortcuts import render

# Create your views here.

def index(request):
    """首页"""
    return render(request,"index.html")

 

 3)在urls.py中配置index访问的url:

import xadmin
from users import views

urlpatterns = [
    path('xadmin/', xadmin.site.urls),
    path('index/', views.index, name = 'index'), # 新增
]

 

 

1-2、登录页面

 login.html页面:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" >
    <title>慕学在线网登录</title>
    <link rel="stylesheet" type="text/css" href="/static/css/reset.css">
    <link rel="stylesheet" type="text/css" href="/static/css/login.css">
</head>
<body>
<div class="dialog" id="jsDialog">
<!--提示弹出框-->
<div class="successbox dialogbox" id="jsSuccessTips">
    <h1>成功提交</h1>
    <div class="close jsCloseDialog"><img src="/static/images/dig_close.png"/></div>
    <div class="cont">
        <h2>您的需求提交成功!</h2>
        <p></p>
    </div>
</div>
<div  class="noactivebox dialogbox" id="jsUnactiveForm" >
    <h1>邮件验证提示</h1>
    <div class="close jsCloseDialog"><img src="/static/images/dig_close.png"/></div>
    <div class="center">
        <img src="/static/images/send.png"/>
        <p>我们已经向您的邮箱<span class="green" id="jsEmailToActive">12@13.com</span>发送了邮件,<br/>为保证您的账号安全,请及时验证邮箱</p>
        <p class="a"><a class="btn" id="jsGoToEmail" target="_blank" href="http://mail.qq.com">去邮箱验证</a></p>
        <p class="zy_success upmove"></p>
        <p style="display: none;" class="sendE2">没收到,您可以查看您的垃圾邮件和被过滤邮件,也可以再次发送验证邮件(<span class="c5c">60s</span>)</p>
        <p class="sendE">没收到,您可以查看您的垃圾邮件和被过滤邮件,<br/>也可以<span class="c5c green" id="jsSenEmailAgin" style="cursor: pointer;">再次发送验证邮件</span></p>
    </div>
</div>
</div>
<div class="bg" id="dialogBg"></div>
<header>
    <div class="c-box fff-box">
        <div class="wp header-box">
            <p class="fl hd-tips">慕学在线网,在线学习平台!</p>
            <ul class="fr hd-bar">
                <li>服务电话:<span>33333333</span></li>
                <li class="active"><a href="login.html">[登录]</a></li>
                <li><a href="register.html">[注册]</a></li>
            </ul>
        </div>
    </div>
</header>
<section>
    <div class="c-box bg-box">
        <div class="login-box clearfix">
            <div class="hd-login clearfix">
                <a class="index-logo" href="/index/"></a>
                <h1>用户登录</h1>
                <a class="index-font" href="/index/">回到首页</a>
            </div>
            <div class="fl slide">
                <div class="imgslide">
                    <ul class="imgs">
                            <li><a href=""><img width="483" height="472" src="/static/images/mysql.jpg" /></a></li>
                            <li><a href=""><img width="483" height="472" src="/static/images/mysql.jpg" /></a></li>
                            <li><a href=""><img width="483" height="472" src="/static/images/mysql.jpg" /></a></li>
                    </ul>
                </div>
                <div class="unslider-arrow prev"></div>
                <div class="unslider-arrow next"></div>
            </div>
            <div class="fl form-box">
                <h2>帐号登录</h2>
                <form action="/login/" method="post" autocomplete="off">
                    {% csrf_token %}
{#                    <input type='hidden' name='csrfmiddlewaretoken' value='mymQDzHWl2REXIfPMg2mJaLqDfaS1sD5' />#}
                    <div class="form-group marb20 ">
                        <label>用&nbsp;户&nbsp;名</label>
                        <input name="username" id="account_l" type="text" placeholder="手机号/邮箱" />
                    </div>
                    <div class="form-group marb8 ">
                        <label>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码</label>
                        <input name="password" id="password_l" type="password" placeholder="请输入您的密码" />
                    </div>
                    <div class="error btns login-form-tips" id="jsLoginTips">{{ msg }}</div>
                     <div class="auto-box marb38">
                        <a class="fr" href="forgetpwd.html">忘记密码?</a>
                     </div>
                     <input class="btn btn-green" id="jsLoginBtn" type="submit" value="立即登录 > " />
{#                <input type='hidden' name='csrfmiddlewaretoken' value='5I2SlleZJOMUX9QbwYLUIAOshdrdpRcy' />#}
                </form>
                <p class="form-p">没有慕学在线网帐号?<a href="register.html">[立即注册]</a></p>
            </div>
        </div>
    </div>
</section>
<script src="/static/js/jquery.min.js" type="text/javascript"></script>
<script src="/static/js/unslider.js" type="text/javascript"></script>
<script src="/static/js/login.js"  type="text/javascript"></script>
</body>
</html>
login.html

 

 views:

登录相关的操作需要用到django自带的auth验证,验证流程:form表单验证:字段是否正确 → authenticate验证:账号密码是否正确

首先新建forms.py文件,创建loginForm,用于验证登录表单:

class LoginForm(forms.Form):
    '''登录验证表单'''
    username = forms.CharField(required=True)
    password = forms.CharField(required=True,min_length=5)

 

其次,登录验证是会用到django自带authenticate验证,

1)在setting.py中配置:

# 找到CustomBackend所在的地方
AUTHENTICATION_BACKENDS = ( # 登录认证设置
    'MxOnline.views.CustomBackend',
)

 

2)在views.py中新增CustomBackend类:

from django.contrib.auth.backends import ModelBackend
from users.models import UserProfile
from django.db.models import Q

class CustomBackend(ModelBackend):
    """
    用于mx_login下的authenticate,
    setting中需配置全局路径AUTHENTICATION_BACKENDS,当用户登录验证时,用到mx_login下的authenticate进行验证,会
    跳到此处进行验证
    """
    def authenticate(self, request, username=None, password=None, **kwargs):# 重写authenticate方法
        try:
            # 不希望用户存在两个,get的结果只能有一个,否则报错
            user = UserProfile.objects.get(Q(username=username)|Q(email=username))

            # django的后台中密码是加密处理的,拿到客户登录的密码需要加密后才能对比判断,所以不能直接password==password
            # UserProfile继承的AbstractUser中有check_password()方法,会直接将传入的密码加密后于后台的作比较:
            if user.check_password(password):# 如果为False,则密码不一致,否则密码正确
                return user
        except Exception as e:
            return None
View Code

 

views.py登录完整代码:

class CustomBackend(ModelBackend):
    """
    用于mx_login下的authenticate,
    setting中需配置全局路径AUTHENTICATION_BACKENDS,当用户登录验证时,用到mx_login下的authenticate进行验证,会
    跳到此处进行验证
    """
    def authenticate(self, request, username=None, password=None, **kwargs):# 重写authenticate方法
        try:
            # 不希望用户存在两个,get的结果只能有一个,否则报错
            user = UserProfile.objects.get(Q(username=username)|Q(email=username))

            # django的后台中密码是加密处理的,拿到客户登录的密码需要加密后才能对比判断,所以不能直接password==password
            # UserProfile继承的AbstractUser中有check_password()方法,会直接将传入的密码加密后于后台的作比较:
            if user.check_password(password):# 如果为False,则密码不一致,否则密码正确
                return user
        except Exception as e:
            return None

def mx_login(request):
    """登录"""
    if request.method == "POST":
        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():# form验证通过
            # 获取用户提交的用户名和密码
            user_name = request.POST.get('username', None)
            pass_word = request.POST.get('password', None)
            # 成功返回user对象,失败None
            user = authenticate(username=user_name, password=pass_word)
            # 如果不是null说明验证成功
            if user:
                # if user.is_active:
                #     # 只有注册激活才能登录
                #     login(request, user)
                #     return HttpResponseRedirect(reverse('index'))
                # request.session["is_login"] = True
                # request.session["username"] = user_name
                # request.session.set_expiry(5)
                login(request,user)
                return redirect("/index/")
                # else:
                #     return render(request, 'login.html', {'msg': '用户名或密码错误', 'login_form': login_form})
            # 账号或密码错误
            else:
                return render(request, 'login.html', {'msg': '用户名或密码错误'})
        else:
            return render(request, 'login.html', {'login_form':login_form})

    return render(request,'login.html')
View Code

 

 

补充:关于request下session的常用内置方法:

# 类似字典数据类型的内置方法
        keys()
        items()
        setdefault()
        clear()


        # 它还有下面的方法:
        flush()
            # 删除当前的会话数据和会话cookie。经常用在用户退出后,删除会话。

        set_test_cookie()
            # 设置一个测试cookie,用于探测用户浏览器是否支持cookies。由于cookie的工作机制,你只有在下次用户请求的时候才可以测试。
        test_cookie_worked()
            # 返回True或者False,取决于用户的浏览器是否接受测试cookie。你必须在之前先调用set_test_cookie()方法。
        delete_test_cookie()
            # 删除测试cookie。
        set_expiry(value)
            # 设置cookie的有效期。可以传递不同类型的参数值:
        • 如果值是一个整数,session将在对应的秒数后失效。例如request.session.set_expiry(300) 将在300秒后失效.
        • 如果值是一个datetime或者timedelta对象, 会话将在指定的日期失效
        • 如果为0,在用户关闭浏览器后失效
        • 如果为None,则将使用全局会话失效策略
        失效时间从上一次会话被修改的时刻开始计时。

        get_expiry_age()
            # 返回多少秒后失效的秒数。对于没有自定义失效时间的会话,这等同于SESSION_COOKIE_AGE.
            # 这个方法接受2个可选的关键字参数
        • modification:会话的最后修改时间(datetime对象)。默认是当前时间。
        •expiry: 会话失效信息,可以是datetime对象,也可以是int或None

        get_expiry_date()
            # 和上面的方法类似,只是返回的是日期

        get_expire_at_browser_close()
            # 返回True或False,根据用户会话是否是浏览器关闭后就结束。

        clear_expired()
            # 删除已经失效的会话数据。
        cycle_key()
            # 创建一个新的会话秘钥用于保持当前的会话数据。django.contrib.auth.login() 会调用这个方法。
session

 

1-3、退出登录操作

 views.py:

def mx_logout(request):
    """退出登录"""
    logout(request)
    return render(request,'index.html')

 

url.py: 

urlpatterns = [
    path('logout/', views.mx_logout, name = 'logout'),
]

 

 

1-4、用户注册

 1)用户注册,有涉及到验证码,使用验证码需要用到Captcha(url:https://github.com/mbi/django-simple-captcha

首先,需要安装captcha:

pip install  django-simple-captcha

 

接着在我们项目的setting.py中的INSTALLED_APPS注册captcha:

INSTALLED_APPS = [
    ……
    'captcha',
    ……
]

 

然后配置我们的urls.py:

from django.urls import path,include,re_path


urlpatterns = [
    path('xadmin/', xadmin.site.urls),
    path('index/', views.index, name = 'index'),
    path('login/', views.mx_login, name = 'login'),
    path('logout/', views.mx_logout, name = 'logout'),
    # 验证码
    re_path(r'^captcha', include('captcha.urls')),  #新增
]

 

这样,在用户注册的时候我们就可以加入验证码的使用了:

 在forms.py中新增RegisterForm类 :

from captcha.fields import CaptchaField

class RegisterForm(forms.Form):
    '''注册验证表单'''
    email = forms.EmailField(required=True)
    password = forms.CharField(required=True,min_length=5)
    # 验证码
    captcha = CaptchaField(error_messages={'invalid':'验证码错误'})

 

然后开始编写用户注册这块,首先是html:

 关于静态文件链接:<link rel="stylesheet" type="text/css" href="/static/css/login.css">,有两种方式:

  第一种就是用上面的方法,直接用/static/css/...,这种是绝对路径,固定不会变得路径

  第二种是比较灵活的,需要在HTML中先导入staticfiles,用法:{% load staticfiles %} ,然后静态文件链接可以这样表示:<link rel="stylesheet" type="text/css" href="{% static 'css/login.css' %}">,这种比较灵活,当转移项目需要改静态文件路径时,只需要在setting中更改:STATIC_URL = '/static/' ,即能一次性改动全页面的静态文件路径

1)处理views.py中关于注册的逻辑:

  1. 返回注册html页面
  2. post操作时,通过form表单判断字段是否合法
  3. from表单通过后,判断用户名是否存在
  4. 都通过时,需要先将密码通过django自带的make_password()方法进行加密再保存
  5. 注册成功,需要给客户发送邮件激活

 

 

 

 

 

 

 

posted on 2018-08-31 02:20  Eric_nan  阅读(305)  评论(0编辑  收藏  举报