Easy Tutorial
❮ Django Routers Django Form ❯

Django Cookies and Sessions

A cookie is a text file stored on the client's computer that retains various tracking information.

Identifying returning users involves three steps:

HTTP is a "stateless" protocol, meaning each time the client retrieves a webpage, the client opens a separate connection to the web server, and the server does not automatically retain any record of previous client requests.

However, there are three ways to maintain a session between the web client and the web server:

Cookies

A web server can assign a unique session ID as a cookie for each web client, which can be used to identify subsequent requests from the client.

In web development, sessions are used for session tracking, with sessions relying on cookie technology.

Cookie Syntax in Django

Setting a cookie:

rep.set_cookie(key, value, ...) 
rep.set_signed_cookie(key, value, salt='encryption salt', ...)

Getting a cookie:

request.COOKIES.get(key)

Deleting a cookie:

rep = HttpResponse || render || redirect 
rep.delete_cookie(key)

Creating Applications and Models

models.py

class UserInfo(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=64)

urls.py

from django.contrib import admin
from django.urls import path
from cookie import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', views.login),
    path('index/', views.index),
    path('logout/', views.logout),
    path('order/', views.order)

views.py

def login(request):
    if request.method == "GET":
        return render(request, "login.html")
    username = request.POST.get("username")
    password = request.POST.get("pwd")

    user_obj = models.UserInfo.objects.filter(username=username, password=password).first()
    print(user_obj.username)

    if not user_obj:
        return redirect("/login/")
    else:
        rep = redirect("/index/")
        rep.set_cookie("is_login", True)
        return rep

def index(request):
    print(request.COOKIES.get('is_login'))
    status = request.COOKIES.get('is_login') # Receives the browser's subsequent request, checks if the browser carries the cookie from the successful login response
    if not status:
        return redirect('/login/')
    return render(request, "index.html")

def logout(request):
    rep = redirect('/login/')
    rep.delete_cookie("is_login")
    return rep # Executes when logging out, deletes the cookie, no longer saves user status, and redirects to the login page
def order(request):
    print(request.COOKIES.get('is_login'))
    status = request.COOKIES.get('is_login')
    if not status:
        return redirect('/login/')
    return render(request, "order.html")

The following creates three template files: login.html, index.html, and order.html.

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h3>User Login</h3>
<form action="" method="post">
    {% csrf_token %}
    <p>Username: <input type="text" name="username"></p>
    <p>Password: <input type="password" name="pwd"></p>
    <input type="submit">
</form>

</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h2>Index Page...</h2>

<a href="/logout/">Logout</a>

</body>
</html>

order.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h2>Order Page...</h2>

<a href="/logout/">Logout</a>

</body>
</html>

The session (a key-value pair stored on the server-side) allows the server to create a unique session object for each user's browser. Since the session is exclusive to the user's browser, data can be stored in the session and retrieved by other web resources on the server when the user accesses them.

Working Principle

Note: The django.session table stores browser information, not individual user information. Therefore, multiple user requests from the same browser only save one record (latter overrides former), while multiple browser requests save multiple records.

Cookies弥补了HTTP无状态的不足,让服务器知道来的人是"谁",但是cookie以文本的形式保存在浏览器端,安全性较差,且最大只支持4096字节,所以只通过cookie识别不同的用户,然后,在对应的session里保存私密的信息以及超过4096字节的文本。

Session setting:

request.session["key"] = value

Execution steps:

urlpatterns = [ path('session_login/', session_views.login), path('s_index/', session_views.s_index), path('s_logout/', session_views.s_logout), ]


Creating view functions:

## views.py

def login(request): if request.method == "GET": return render(request, "login.html") username = request.POST.get("username") password = request.POST.get("pwd")

user_obj = models.UserInfo.objects.filter(username=username, password=password).first()
print(user_obj.username)

if not user_obj:
    return redirect("/session_login/")
else:
    request.session['is_login'] = True
    request.session['user1'] = username
    return redirect("/s_index/")

def s_index(request): status = request.session.get('is_login') if not status: return redirect('/session_login/') return render(request, "s_index.html")

def s_logout(request): # del request.session["is_login"] # Delete a specific key-value pair from session_data request.session.flush() # Delete the entire record including (session_key, session_data, expire_date) fields return redirect('/session_login/')


Template file:

## s_index.html

<html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>session_index page...{{ request.session.user1 }}</h2> <a href="/s_logout/">Logout</a> </body> </html> ```

The result is shown in the following image:

❮ Django Routers Django Form ❯