django 快速实现完整登录系统(cookie)
經(jīng)過前面幾節(jié)的練習(xí),我們已經(jīng)熟悉了django 的套路,這里來實現(xiàn)一個比較完整的登陸系統(tǒng),其中包括注冊、登陸、以及cookie的使用。
本操作的環(huán)境:
===================
deepin?linux?2013(基于ubuntu)
python?2.7
Django?1.6.2
===================
?
創(chuàng)建項目與應(yīng)用 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ??
?
#創(chuàng)建項目 fnngj@fnngj-H24X:~/djpy$ django-admin.py startproject mysite5 fnngj@fnngj-H24X:~/djpy$ cd mysite5 #在項目下創(chuàng)建一個online應(yīng)用 fnngj@fnngj-H24X:~/djpy/mysite5$ python manage.py startapp online目錄結(jié)構(gòu)如下:
打開mysite5/mysite5/settings.py文件,將應(yīng)用添加進去:
# Application definition INSTALLED_APPS = ('django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','online', )?
?
設(shè)計數(shù)據(jù)庫 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
?
打開mysite5/online/models.py文件,添加如下內(nèi)容:
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創(chuàng)建數(shù)據(jù)庫,創(chuàng)建User表,用戶名和密碼兩個字段。
下面進行數(shù)據(jù)庫的同步:
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/noUsername (leave blank to use 'fnngj'): 用戶名(默認當(dāng)前系統(tǒng)用戶名) 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?中所創(chuàng)建的User類。
?
?
配置URL ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
?
打開mysite5/mysite5/urls.py:
from django.conf.urls import patterns, include, urlfrom 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/目錄下創(chuàng)建urls.py文件:
from django.conf.urls import patterns, url from online import viewsurlpatterns = 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/???注銷
?
?
創(chuàng)建視圖 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
?
打開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():#獲得表單數(shù)據(jù)username = uf.cleaned_data['username']password = uf.cleaned_data['password']#添加到數(shù)據(jù)庫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']#獲取的表單數(shù)據(jù)與數(shù)據(jù)庫進行比較user = User.objects.filter(username__exact = username,password__exact = password)if user:#比較成功,跳轉(zhuǎn)indexresponse = HttpResponseRedirect('/online/index/')#將username寫入瀏覽器cookie,失效時間為3600response.set_cookie('username',username,3600)return responseelse:#比較失敗,還在loginreturn 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里保存usernameresponse.delete_cookie('username')return response這里實現(xiàn)了所有注冊,登陸邏輯,中間用到cookie創(chuàng)建,讀取,刪除操作等。
?
?
創(chuàng)建模板 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
?
先在mysite5/online/目錄下創(chuàng)建templates目錄,接著在mysite5/online/templates/目錄下創(chuàng)建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/目錄下創(chuàng)建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/目錄下創(chuàng)建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>?
設(shè)置模板路徑
打開mysite5/mysite5/settings.py文件,在底部添加:
#template TEMPLATE_DIRS=('/home/fnngj/djpy/mysite5/online/templates' )?
?
使用功能 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?
?
注冊
先注冊用戶:
注冊成功,提示“regist?success!!”
?
登陸
執(zhí)行登陸操作,通過讀取瀏覽器cookie?來獲取用戶名
?
查看cookie
?
登陸成功
通過點擊“退出”鏈接退出,再次訪問http://127.0.0.1:8000/online/index/?將不會顯示用戶名信息。
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的django 快速实现完整登录系统(cookie)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用Python操作Oracle
- 下一篇: Windows8 Metro开发 (03