登录页面和首页分开

index.html:

<html>

 <head>

  <title>首页</title>

 </head>

 <body>

   <div>这是首页,当前登录用户是:<span style="color:green">`currentuser`</span>

   </div>

 </body>

</html>


userlogin.html

<style>

.bb{border:2px solid red ;width: 600px;margin: 150px auto}

.textcenter{text-align: center}

.full{width:100%}

div{line-height:40px}

.greenspan{color:green}

 .redspan{color:red}


</style>

<form method="POST">

<div class="bb textcenter">

<div  class="full">

    请输入用户名:<input type="text" name="txtUserName"/>

  </div>

  

   <div class="full">

    请输入密   码:<input type="password" name="txtUserPass"/>

  </div>

  <div class="full">

    选择地区:<select name="userArea">

     <option value="0">--请选择--</option>

      {% for aa in areas %}

      <option value="`aa`.`id`">`aa`.`dd`</option>

      {% endfor %}

     </select>

  </div>

  <div class="full">

   <input type="submit" value="登录"/>

  </div> 

</div>

</form>

{{result|safe}}


urls.py

urlpatterns = [

    #url(r'^admin/', include(admin.site.urls)),

    url(r'^index','myindex.bb.hi' ),

    url(r'^login', 'myindex.bb.login')

]



服务端代码

登陆逻辑:

UserClass.py

#coding:utf-8

class UserLogin:

    UserName=""

    UserPass=""

    def __init__(self,uname,upass):

        self.UserName=uname

        self.UserPass=upass

    def Login(self):

        if self.UserName=="shenyi" and self.UserPass=="123":

            return True

        return False



业务逻辑:

如果登陆成功,就设置cookies,跳转index

# -*- coding: utf-8 -*-

from django.http.response import HttpResponse

from django.shortcuts import render_to_response

import user

from UserClass import UserLogin



def hi(request):

   

    dataset={"result":"","currentuser":"游客"}

  

    if request.COOKIES.get("userlogin_username") != None:

        dataset["currentuser"]=request.COOKIES.get("userlogin_username")

    

    myResponse=render_to_response("index.html",dataset)

    return myResponse


def login(request):

    beijin = {"id":1,"dd":"北京"}

    shanghai = {"id":2,"dd":"上海"}

    userAreas = [beijin,shanghai]

    dataset = {'result':'',"areas":userAreas}

    

    if request.method=="POST":

        getUserName=request.POST.get("txtUserName");

        getUserPass=request.POST.get("txtUserPass")

        uLogin=UserLogin(getUserName,getUserPass)

        if uLogin.Login():

           myResponse=HttpResponse("<script>self.location='/index'</script>")

           myResponse.set_cookie("userlogin_username", getUserName, 3600)  #设置cookie

           return myResponse

        else:

           dataset["result"]="用户名和密码错误"

    myResponse=render_to_response("userlogin.html",dataset)

    return myResponse


from UserClass import UserLogin

为从文件中导入类



cookie

就是通过浏览器和服务器沟通后,私下保存在用户电脑里某个文件夹的一个文件。