通過前面幾節的練習,咱們已經熟悉了django 的套路,這裏來實現一個比較完整的登錄系統,其中包括註冊、登錄、以及cookie的使用。html
本操做的環境:python
===================linux
deepin linux 2013(基於ubuntu)數據庫
python 2.7django
Django 1.6.2ubuntu
===================瀏覽器
建立項目與應用 cookie
#建立項目
fnngj@fnngj-H24X:~/djpy$ django-admin.py startproject mysite5
fnngj@fnngj-H24X:~/djpy$ cd mysite5
#在項目下建立一個online應用
fnngj@fnngj-H24X:~/djpy/mysite5$ python manage.py startapp online
目錄結構以下:session
打開mysite5/mysite5/settings.py文件,將應用添加進去:app
# Application definition
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'online', )
設計數據庫
打開mysite5/online/models.py文件,添加以下內容:
from django.db import models # Create your models here.
class User(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) def __unicode__(self): return self.username
建立數據庫,建立User表,用戶名和密碼兩個字段。
下面進行數據庫的同步:
fnngj@fnngj-H24X:~/djpy/mysite5$ python manage.py syncdb
Creating tables ...
Creating table django_admin_log
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_groups
Creating table auth_user_user_permissions
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table online_user
You just installed Django's auth system, which means you don't have any superusers defined.
Would you like to create one now? (yes/no): yes 輸入yes/no
Username (leave blank to use 'fnngj'): 用戶名(默認當前系統用戶名)
Email address: fnngj@126.com 郵箱地址
Password: 密碼
Password (again): 確認密碼
Superuser created successfully.
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
最後生成的 online_user 表就是咱們models.py 中所建立的User類。
配置URL
打開mysite5/mysite5/urls.py:
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples:
# url(r'^$', 'mysite5.views.home', name='home'),
url(r'^admin/', include(admin.site.urls)), url(r'^online/', include('online.urls')), )
在mysite5/online/目錄下建立urls.py文件:
from django.conf.urls import patterns, url from online import views urlpatterns = patterns('', url(r'^$', views.login, name='login'), url(r'^login/$',views.login,name = 'login'), url(r'^regist/$',views.regist,name = 'regist'), url(r'^index/$',views.index,name = 'index'), url(r'^logout/$',views.logout,name = 'logout'), )
http://127.0.0.1:8000/online/ 登錄頁
http://127.0.0.1:8000/online/login/ 登錄頁
http://127.0.0.1:8000/online/regist/ 註冊頁
http://127.0.0.1:8000/online/index/ 登錄成功頁
http://127.0.0.1:8000/online/logout/ 註銷
建立視圖
打開mysite5/online/views.py 文件:
#coding=utf-8
from django.shortcuts import render,render_to_response from django.http import HttpResponse,HttpResponseRedirect from django.template import RequestContext from django import forms from models import User #表單
class UserForm(forms.Form): username = forms.CharField(label='用戶名',max_length=100) password = forms.CharField(label='密碼',widget=forms.PasswordInput()) #註冊
def regist(req): if req.method == 'POST': uf = UserForm(req.POST) if uf.is_valid(): #得到表單數據
username = uf.cleaned_data['username'] password = uf.cleaned_data['password'] #添加到數據庫
User.objects.create(username= username,password=password) return HttpResponse('regist success!!') else: uf = UserForm() return render_to_response('regist.html',{'uf':uf}, context_instance=RequestContext(req)) #登錄
def login(req): if req.method == 'POST': uf = UserForm(req.POST) if uf.is_valid(): #獲取表單用戶密碼
username = uf.cleaned_data['username'] password = uf.cleaned_data['password'] #獲取的表單數據與數據庫進行比較
user = User.objects.filter(username__exact = username,password__exact = password) if user: #比較成功,跳轉index
response = HttpResponseRedirect('/online/index/') #將username寫入瀏覽器cookie,失效時間爲3600
response.set_cookie('username',username,3600) return response else: #比較失敗,還在login
return HttpResponseRedirect('/online/login/') else: uf = UserForm() return render_to_response('login.html',{'uf':uf},context_instance=RequestContext(req)) #登錄成功
def index(req): username = req.COOKIES.get('username','') return render_to_response('index.html' ,{'username':username}) #退出
def logout(req): response = HttpResponse('logout !!') #清理cookie裏保存username
response.delete_cookie('username') return response
這裏實現了全部註冊,登錄邏輯,中間用到cookie建立,讀取,刪除操做等。
建立模板
先在mysite5/online/目錄下建立templates目錄,接着在mysite5/online/templates/目錄下建立regist.html 文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>註冊</title>
</head>
<body>
<h1>註冊頁面:</h1>
<form method = 'post' enctype="multipart/form-data"> {% csrf_token %} {{uf.as_p}} <input type="submit" value = "ok" />
</form>
<br>
<a href="http://127.0.0.1:8000/online/login/">登錄</a>
</body>
</html>
mysite5/online/templates/目錄下建立login.html 文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>登錄</title>
</head>
<body>
<h1>登錄頁面:</h1>
<form method = 'post' enctype="multipart/form-data"> {% csrf_token %} {{uf.as_p}} <input type="submit" value = "ok" />
</form>
<br>
<a href="http://127.0.0.1:8000/online/regist/">註冊</a>
</body>
</html>
mysite5/online/templates/目錄下建立index.html 文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>
<h1>welcome {{username}} !</h1>
<br>
<a href="http://127.0.0.1:8000/online/logout/">退出</a>
</body>
</html>
設置模板路徑
打開mysite5/mysite5/settings.py文件,在底部添加:
#template
TEMPLATE_DIRS=( '/home/fnngj/djpy/mysite5/online/templates' )
使用功能
註冊
先註冊用戶:
註冊成功,提示「regist success!!」
登錄
執行登錄操做,經過讀取瀏覽器cookie 來獲取用戶名
查看cookie
登錄成功
經過點擊「退出」連接退出,再次訪問http://127.0.0.1:8000/online/index/ 將不會顯示用戶名信息。