Home >Backend Development >PHP Tutorial >Compare cookie and session instance operations in Django
This article introduces cookie and session operations in Django through sample code. Friends who need it can refer to it
Add cookies:
def login(req): if req.method=="POST": uf = UserInfoForm(req.POST) if uf.is_valid(): username = uf.cleaned_data["username"] password = uf.cleaned_data["password"] print username,password users = UserInfo.objects.filter(username=username,password=password) if users: response = HttpResponseRedirect("/index/") response.set_cookie("username",username,3600) return response else: return HttpResponseRedirect("/login") # return HttpResponseRedirect() else: uf = UserInfoForm() return render_to_response("login.html",{"uf":uf})
Get cookie:
def index(req): username = req.COOKIES.get("username","")return render_to_response("index.html",{"username":username})
Delete cookie:
Response.delete_cookie("username")
Add session:
def sesion(req): if req.method == "POST": uf = UserInfoForm(req.POST) if uf.is_valid(): username = uf.cleaned_data["username"] req.session["username"] = username return HttpResponseRedirect("/index/") else: uf = UserInfoForm() return render_to_response("LoadFile.html",{"uf":uf})
Get session:
def index(req): username = req.session.get("username","") return render_to_response("index.html",{"username":username})
Delete session:
##
del req.session['username']
The above is the detailed content of Compare cookie and session instance operations in Django. For more information, please follow other related articles on the PHP Chinese website!