django 学习-17 Django会话Session

时间:2022-05-17 16:20:48

session   类似于字典的一个对象,是可读可写的

跟cookie的变化不大而且还显得简单

在这里我只说一下改变的地方

1、vim blog/views.py

if uf.is_valid():
                        username = uf.cleaned_data['username']
                        password = uf.cleaned_data['password']
                        users = User.objects.filter(username__exact=username,password__exact=password)

req.session['username'] = username          直接调取

         if users:
                                response =  HttpResponseRedirect('/index/')
                                response.set_cookie('username',username,3600)
                                return response
                        else:
                                return HttpResponseRedirect('/login/')
        else:
                uf = UserForm()
        return render_to_response('login.html',{'uf':uf})

def index(req):
        username = req.session.get('username',' ')                        登陆上去网页会有一条session记录
        return render_to_response('index.html', {'username':username})
def logout(req):
#       response = HttpResponse('logout')
#       response.delete_cookie('username')
        del req.session['username']                            直接删除,
        return HttpResponse('logout ok')