django 学习-16 Django会话Cookie

1、django.admin.py  startproject   cs3

cd cs3

django.admin.py   startapp   blog

2、    vim urls.py

url(r'^regist/$','blog.views.regist'),       注册
    url(r'^login/$','blog.views.login'),   登录
    url(r'^index/$','blog.views.index'),      跳转界面
    url(r'^logout/$','blog.views.logout'),    注销
)

3、vim blog/views.py

from   django  import  forms
from django.http  import  HttpResponse
from django.shortcuts  import  render_to_response
from  models  import User
class UserForm(forms.Form):
        username =  forms.CharField()
        password = forms.CharField(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('ok')
        else:
                uf = UserForm
        return render_to_response('regist.html',{'uf':uf})

4、vim blog/templates/regist.html

<form method="post">
{{uf.as_p}}
<input type="submit" value='nice'/ >
</form>
5、      python  manage.py syncdb

  python manage.py   runserver

进入页面去试一试127.0.0.1:8000/regist

6、vim blog/views.py

增加这些

 from django.http import HttpResponseRedirect

 def login(req):
 23         if req.method == "POST":
 24                 uf = UserForm(req.POST)
 25                 if uf.is_valid():
 26                         username = uf.cleaned_data['username']
 27                         password = uf.cleaned_data['password']
 28                         users = User.objects.filter(username__exact=username,password__exact=password)
 29                         if users:
 30                                 return HttpResponseRedirect('/index/')
 31                         else:
 32                                 return HttpResponseRedirect('/login/')
 33         else:
 34                 uf = UserForm()
 35         return render_to_response('login.html',{'uf':uf})
 36 def index(req):
 37         return HttpResponse('ok')

再去试一试127.0.0.1:8000/login   会跳转到index   127.0.0.1:8000/index   直接访问index会返回OK

6、vim blog/views.py      顺便cp  regist.html  login.html

def index(req):
        username = req.COOKIES.get('username','')           用cook获取用户名,在网页界面还可以去查找,在freference-->privacy-->选use custome                                                         for settings  history -->show cookies就可以看到了

        return render_to_response('index.html', {'username':username})
def logout(req):
        response = HttpResponse('logout')
        response.delete_cookie('username')                        cookie 的删除方式
        return response
    7  、 vim blog/templates/index.html        

  <div>

<h1>welcome {{username}}</h1>
<a href='/logout/'>logout</a>
</div>
这样index下就会有个logout可以选择退出

posted @ 2016-01-15 22:24  Lz阿飞  阅读(152)  评论(0编辑  收藏  举报