目录[-]
前言
对于web开来说,用户登陆、注册、文件上传等是最基础的功能,针对不同的web框架,相关的文章非常多,但搜索之后发现大多都不具有完整性,对于想学习web开发的新手来说不具有很强的操作性;对于web应用来说,包括数据库的创建,前端页面的开发,以及中间逻辑层的处理三部分。
本系列以可操作性为主,介绍如何通过django web框架来实现一些简单的功能。每一章都具有完整性和独立性。使用新手在动手做的过程中体会web开发的过程,过程中细节请参考相关文档。
本操作的环境:
===================
deepin linux 2013(基于ubuntu)
python 2.7
Django 1.6.2
===================
创建项目与应用
#创建项目
fnngj@fnngj-H24X:~/djpy$ django-admin.py startproject mysite3
fnngj@fnngj-H24X:~/djpy$ cd mysite3
#在项目下创建一个account应用
fnngj@fnngj-H24X:~/djpy/mysite3$ python manage.py startapp account
目录结构如下:
打开mysite3/mysite3/settings.py文件,将应用添加进去:
# Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'account', )
设计Model(数据库)
打开mysite3/account/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) email = models.EmailField()
按照惯例先创建数据库,创建三个字段,用户存放用户名、密码、email 地址等。
下面进行数据库的同步
fnngj@fnngj-H24X:~/djpy/mysite3$ 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 account_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)
最后生成的 account_user 表就是我们models.py 中所创建的User类。Django 提供了他们之间的对应关系。
创建视图(逻辑层)
打开mysite3/account/views.py 文件:
#coding=utf-8 from django.shortcuts import render from django import forms from django.shortcuts import render_to_response from django.http import HttpResponse,HttpResponseRedirect from django.template import RequestContext from account.models import User #定义表单模型 class UserForm(forms.Form): username = forms.CharField(label='用户名:',max_length=100) passworld = forms.CharField(label='密码:',widget=forms.PasswordInput()) email = forms.EmailField(label='电子邮件:') # Create your views here. def register(request): if request.method == "POST": uf = UserForm(request.POST) if uf.is_valid(): #获取表单信息 username = uf.cleaned_data['username'] passworld = uf.cleaned_data['passworld'] email = uf.cleaned_data['email'] #将表单写入数据库 user = User() user.username = username user.passworld = passworld user.email = email user.save() #返回注册成功页面 return render_to_response('success.html',{'username':username}) else: uf = UserForm() return render_to_response('register.html',{'uf':uf})
的这个逻辑中主要做了几件事,首先提供给用户一个注册页面(register.html),UserForm类定义了表单在注册页面上的显示。接受用户填写的表单信息,然后将表单信息写入到数据库,最后返回给用户一个注册成功的页面(success.html)
创建模板文件(前端页面)
在逻辑层提到了两个页面,一个注册页,一个注册成功页面。所以我们要把这两个页面创建出来。
先在mysite3/account/目录下创建templates目录,接着在mysite3/account/templates/目录下创建register.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> <style type="text/css"> body{color:#efd;background:#453;padding:0 5em;margin:0} h1{padding:2em 1em;background:#675} h2{color:#bf8;border-top:1px dotted #fff;margin-top:2em} p{margin:1em 0} </style> <body> <h1>注册页面:</h1> <form method = 'post' enctype="multipart/form-data"> {{uf.as_p}} <input type="submit" value = "ok" /> </form> </body> </html>
mysite3/account/templates/目录下创建success.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>恭喜{{username}},注册成功!</h1> </form> </body> </html>
设置模板路径
打开mysite3/mysite3/settings.py文件,在底部添加:
#template TEMPLATE_DIRS=( '/home/fnngj/djpy/mysite3/account/templates' )
设置URL
设置URL的配置也是django web框架的一大特色。打开mysite3/mysite3/urls.py:
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'mysite3.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^account/', include('account.urls')), )
在mysite3/account/目录下创建urls.py文件:
from django.conf.urls import patterns, url from account import views urlpatterns = patterns('', url(r'^$', views.register, name='register'), url(r'^register/$',views.register,name = 'register'), )
这里人配置表示:访问
http://127.0.0.1:8000/account/
http://127.0.0.1:8000/account/register/
都会指向一个注册页面。
体验注册
当所有工作都完成之后,下面体验一下我们的注册功能吧。
启动服务:
fnngj@fnngj-H24X:~/djpy/mysite3$ python manage.py runserver
Validating models...
0 errors found
May 21, 2014 - 14:31:32
Django version 1.6.2, using settings 'mysite3.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
访问注册页面:
因为在register.html 文件中加了一点样式,所以看上去好看了一点,但作为一个审美的人观念的人无法容忍这样丑陋的页面存在。
以免错误的再次出现,
打开mysite3/mysite3/settings.py文件,将下面一行代码注释:
MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', )
现在可以作为一个用户去填写表单了。
注册的用户哪儿去了?
你依然可以像昨天一样去查询数据库,但为什么不利用admin呢?
打开mysite3/account/models.py文件:
from django.db import models from django.contrib import admin # Create your models here. class User(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) email = models.EmailField() class UserAdmin(admin.ModelAdmin): list_display = ('username','email') admin.site.register(User,UserAdmin)
重新初始化数据库:
fnngj@fnngj-H24X:~/djpy/mysite3$ python manage.py syncdb
Creating tables ...
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
登陆admin 后台
http://127.0.0.1:8000/admin/
登陆所需要的用户名和密码就是我们第一次同步数据库时所设置。
然后我们就看到刚刚注册的那个用户信息。
创建项目与应用
#创建项目 fnngj@fnngj-H24X:~/djpy$ django-admin.py startproject mysite4 fnngj@fnngj-H24X:~/djpy$ cd mysite4 #在项目下创建一个login应用 fnngj@fnngj-H24X:~/djpy/mysite4$ python manage.py startapp login
项目目录结构如下:
打开mysite4/mysite4/settings.py文件,将应用添加进去:
# Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'login', ) …… #顺便注释csrf MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', )
设计model(数据库)
打开mysite4/login/models.py文件,添加如下内容
from django.db import models from django.contrib import admin # Create your models here. class User(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) admin.site.register(User)
创建一个User表,有两个字段username、password
然后,进行数据库的同步:
fnngj@fnngj-H24X:~/djpy/mysite4$ 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 login_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)
配置URL
打开mysite4/mysite4/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'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), )
启动服务
fnngj@fnngj-H24X:~/djpy/mysite4$ python manage.py runserver Validating models... 0 errors found May 21, 2014 - 14:31:32 Django version 1.6.2, using settings 'mysite4.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
访问admin
登录用户名和密码为我们进行数据库同步时所设置的信息。
登录之后,选择add 添加用户。
创建用户,点击save
再次打开mysite4/login/models.py文件,添加如下内容
from django.db import models from django.contrib import admin # Create your models here. class User(models.Model): username = models.CharField(max_length=50) password = models.CharField(max_length=50) class UserAdmin(admin.ModelAdmin): list_display = ('username','password') admin.site.register(User,UserAdmin)
再次刷新,admin后台,如下显示:
创建视图
现在我们已经生成了一个用户信息表,下面要做的就是设计用户登录功能了。
打开mysite4/login/views.py 文件
#coding=utf-8 from django.shortcuts import render,render_to_response from django.http import HttpResponseRedirect from login.models import User from django import forms #定义表单模型 class UserForm(forms.Form): username = forms.CharField(label='用户名:',max_length=100) password = forms.CharField(label='密码:',widget=forms.PasswordInput()) #登录 def login(request): if request.method == 'POST': uf = UserForm(request.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: return render_to_response('success.html',{'username':username}) else: return HttpResponseRedirect('/login/') else: uf = UserForm() return render_to_response('login.html',{'uf':uf})
上面登录的核心是比较,拿到用户填写的表单数据(用户名、密码)与数据库User表中的字段进行比较,根据比较结果,如果成功跳转到success.html页面,如果失败还留在原来页面login.html 。
创建模板
根据视图层的要求,我们需要创建两个页面,success.html 和login.html
先在mysite4/login/目录下创建templates目录,接着在mysite4/login/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> <style type="text/css"> body{color:#efd;background:#453;padding:0 5em;margin:0} h1{padding:2em 1em;background:#675} h2{color:#bf8;border-top:1px dotted #fff;margin-top:2em} p{margin:1em 0} </style> <body> <h1>登录页面:</h1> <form method = 'post' enctype="multipart/form-data"> {{uf.as_p}} <input type="submit" value = "ok" /> </form> </body> </html>
在mysite4/login/templates/目录下创建success.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>恭喜{{username}},登录成功!</h1> </form> </body> </html>
设置模板路径
打开mysite4/mysite4/settings.py文件,在底部添加:
#template TEMPLATE_DIRS=( '/home/fnngj/djpy/mysite4/login/templates' )
配置URL
打开mysite4/mysite4/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'^login/', include('login.urls')), url(r'^admin/', include(admin.site.urls)), )
创建文件mysite4/login/urls.py
from django.conf.urls import patterns, url from login import views urlpatterns = patterns('', url(r'^$', views.login, name='login'), )
启动服务(python manage.py runserver),
访问登录页面(http://127.0.0.1:8000/login/)
用户名、密码正确,点击OK ,跳转到登录成功页面:
创建项目与应用
#创建项目 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
目录结构如下:
打开mysite5/mysite5/settings.py文件,将应用添加进去:
# 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/ 将不会显示用户名信息。