1.设置cookie信息(登陆成功后设置登陆用户名,有效期1小时)
def login(req): if req.method == ‘POST‘: loginform = LoginForm(req.POST) if loginform.is_valid(): print loginform.cleaned_data username = loginform.cleaned_data["username"] password = loginform.cleaned_data["userpwd"] users=RegisterUser.objects.filter(username =username , password =password) print users if users: response= HttpResponseRedirect(‘/app1/index1/‘) response.set_cookie(‘username‘,username,3600) return response else: return HttpResponseRedirect(‘/app1/login/‘) else: loginform = LoginForm() return render_to_response(‘login.html‘,{‘loginform‘:loginform})
2.检查获取当前cookie信息(判断是否登陆)
def index1(req): loginusername = req.COOKIES.get(‘username‘,‘‘) print loginusername islogin=False if loginusername: islogin=True else: islogin=False aus = Author.objects.all() books = Book.objects.all() t= loader.get_template(‘index1.html‘) c=Context({‘aus‘:aus,‘books‘:books,‘islogin‘:islogin,‘loginusername‘:loginusername}) return HttpResponse(t.render(c))
3.删除cookie信息
def loginout(req): response =HttpResponseRedirect(‘/app1/index1/‘) response.delete_cookie(‘username‘) return response
时间: 2024-10-22 08:02:57