session 在这里先说session
配置URL
from django.conf.urls import patterns, include, url
from django.contrib import admin admin.autodiscover() urlpatterns = patterns('',
# Examples:
# url(r'^$', 'csvt11.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)), url(r'^login/$', 'online.views.login'),
url(r'^index/$', 'online.views.index'),
url(r'^logout/$', 'online.views.logout'),
)
创建视图
views.py
#coding=utf-8
from django.shortcuts import render
from django.shortcuts import render,render_to_response
from django.http import HttpResponse,HttpResponseRedirect
from django import forms class UserForm(forms.Form): ##form验证
username = forms.CharField() #用户登录
def login(req):
if req.method == "POST":
uf = UserForm(req.POST)
if uf.is_valid():
username = uf.cleaned_data['username']
#把获取表单的用户名传递给session对象
req.session['username'] = username
return HttpResponseRedirect('/index/')
else:
uf = UserForm()
return render_to_response('login.html',{'uf':uf}) #登录之后跳转页
def index(req):
username = req.session.get('username','anybody')
return render_to_response('index.html',{'username':username}) #注销动作
def logout(req):
del req.session['username'] #删除session
return HttpResponse('logout ok!')
这里用到的就是session创建和删除,代码中有注释。视图是动能实现的核心逻辑,这里调用到了session的相关方法,非常简单,需要说明的是session 是字典的形式存在的,比如一个sessionid 对应一个信息(比如,用户名,密码,添加到购物车的商品等。)
创建模板
login.html
<form method = 'post'>
{{uf.as_p}}
<input type="submit" value = "ok"/>
</form>
index.html
<div>
<h1>welcome {{username}}</h1>
<a href="/logout">logout</a>
</div>
这里没有判断用户密码是否正常的逻辑,所以,输入任意信息都可登录。
看查,session 是用户登录的用户名保存服务器端的数据库中,而客户端(浏览器)产生的只是一个session id ,程序通过读取客户端的session id 来查找对应的用户名,并返回给客户端,从而在客户端的信息。在数据库中并没有看到刚才登录的用户名(Tom),标红色下划线的就是,只是对其进行了加密,所以会看到一串很长的大小写字符串。
在index 页面,点击“logout” 退出后,就删除了客户端的session id 信息,所以,再访问index 页面,就是会看到“weclome anybody”的提示。
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
目录结构如下:
打开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'),
)
创建视图
打开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
登陆成功
Django form上传文件
目录结构
urls.py
from app1 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/',views.register)
]
models.py
from django.db import models # Create your models here. class User(models.Model):
username =models.CharField(max_length=30)
heading =models.FileField(upload_to='./upload') def __str__(self):
return self.username # python manage.py makemigrations
# python manage.py migrate
views.py
from django.shortcuts import render, render_to_response # Create your views here.
from app1 import models
from django import forms
from django.http import HttpResponse class UserForm(forms.Form): ##form验证
username = forms.CharField()
heading = forms.FileField() def register(request):
if request.method == 'POST':
uf = UserForm(request.POST, request.FILES)
if uf.is_valid():
#获取表信息
username = uf.cleaned_data['username']
headimg = uf.cleaned_data['heading']
user = models.User()
#写入数据库
user.username = username
user.heading = headimg
user.save()
return HttpResponse('upload ok!')
else:
uf = UserForm() ##
return render_to_response('register.html', {'uf': uf})
register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>register</h1>
<form method="post" enctype="multipart/form-data">
{{ uf.as_p }} #as_p 拿出所有数据,内部渲染P标签
<input type="submit" value="ok">
</form> </body>
</html>