Home > Backend Development > PHP Tutorial > Compare cookie and session instance operations in Django

Compare cookie and session instance operations in Django

巴扎黑
Release: 2023-03-15 11:26:01
Original
1371 people have browsed it

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})
Copy after login

Get cookie:


def index(req):
  username = req.COOKIES.get("username","")return render_to_response("index.html",{"username":username})
Copy after login

Delete cookie:


  Response.delete_cookie("username")
Copy after login

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})
Copy after login

Get session:


def index(req):
  username = req.session.get("username","")
  return render_to_response("index.html",{"username":username})
Copy after login

Delete session:


##

del req.session['username']
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template