Linux下开发python django程序(Session读写)
1.登陆设置session信息
def loginsession(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: req.session['username']=username return HttpResponseRedirect('/app1/indexsession/') else: return HttpResponseRedirect('/app1/login/') else: loginform = LoginForm() return render_to_response('login.html',{'loginform':loginform})
template中对应的模板页面
<?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> {% if islogin %} <li>登录用户:{{sessionloginname}} <a href="/app1/loginoutsession/">Logout</a></li> {%else %} <li><a href="/app1/loginsession/">Login</a></li> {%endif%} <div> {% for book in books %} <h1>书籍:{{book}}<br></h1> {% for au in book.author.all %} 作者: {{au}} <br/> {%endfor%} {% endfor%} </div> </body> </html>
2.获取session中的用户信息
def indexsession(req): sessionloginname = req.session.get('username','') print 'sessionloginname:'+sessionloginname islogin=False if sessionloginname : 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,'sessionloginname':sessionloginname}) return HttpResponse(t.render(c))
3.删除session中信息
def loginoutsession(req): del req.session['username'] return HttpResponse('loginout ok!!')