2014年11月5日 星期三
Django筆記(12)- 註冊新的使用者
步驟一
修改 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
#使用內建的註冊模型
from django.contrib.auth.forms import UserCreationForm
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
return HttpResponseRedirect('/login/')
else:
form = UserCreationForm()
return render_to_response('register.html',locals())
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) #負責用戶登入狀態的保持
return HttpResponseRedirect('/hello/')
else:
return render_to_response('login.html')
def logout(request):
auth.logout(request)
return HttpResponseRedirect('/login/')
步驟二
新增 mysite/templates/register.html(完整代碼如下)
<html>
<head>
<title> login </title>
<meta charset='utf-8'>
</head>
<body>
<h1>註冊新帳號</h1>
<form action="" method="post">
{{ form.as_p }}
<input type="submit" value="註冊">
</form>
</body>
</html>
步驟三
修改 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),
url(r'^register/$',register),
)
步驟四
修改 mysite/templates/hello.html(完整代碼如下)
<html>
<head>
<title> hello </title>
<meta charset='utf-8'>
</head>
<body>
<p><a href="/register/">註冊</a></p>
{% if request.user.is_authenticated %}
<p>{{request.user}} 您已經登入囉!</p>
<a href="/logout/">登出</a>
{% else %}
<p>您尚未登入!<a href="/login/">登入</a></p>
{% endif %}
</body>
</html>
步驟五
開啟 server 後在網址列打上 127.0.0.1:8000/hello/ 註冊新用戶,並以新用戶登入後觀看結果
上一篇 回目錄
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言