2014年11月5日 星期三
Django筆記(11)- 使用者的登入和登出
步驟一
新增 mysite/templates/login.html(完整代碼如下)
<html>
<head>
<title> login </title>
<meta charset='utf-8'>
</head>
<body>
<form action="" method="post">
<label for="username">用戶名稱:</label>
<input type="text" name="username" value="" id="username"><br>
<label for="password">用戶密碼:</label>
<input type="password" name="password" value="" id="password"><br>
<input type="submit" value="登入" />
</form>
</body>
</html>
步驟二
新增 mysite/templates/hello.html(完整代碼如下)
<html>
<head>
<title> hello </title>
<meta charset='utf-8'>
</head>
<body>
{% if request.user.is_authenticated %}
<p>{{request.user}} 您已經登入囉!</p>
<a href="/logout/">登出</a>
{% else %}
<p>您尚未登入!<a href="/login/">登入</a></p>
{% endif %}
</body>
</html>
步驟三
修改 mysite/mysite/views.py(完整代碼如下)
from django.shortcuts import render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django import template
from django.contrib import auth
def hello(request):
return render_to_response('hello.html',locals())
def login(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/hello/')
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
if user is not None and user.is_active:
auth.login(request, user) #maintain the state of login
return HttpResponseRedirect('/hello/')
else:
return render_to_response('login.html')
def logout(request):
auth.logout(request)
return HttpResponseRedirect('/login/')
步驟四
修改 mysite/mysite/urls.py(完整代碼如下)
from django.conf.urls import patterns, include, url
from django.contrib import admin
from mysite.views import *
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^login/$',login),
url(r'^logout/$',logout),
url(r'^hello/$',hello),
)
步驟五
開啟 server 後~
在網址列打上 127.0.0.1:8000/hello/ 用超級管理員登入並觀看結果
上一篇 回目錄 下一篇
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言