django sets cookie s and session s

Keywords: Python Session Django Database

1 set cookie s

In this case, the application name is cookie

Model model

from django.db import models

from django.db import models
class UserInfo(models.Model):
    username = models.CharField(max_length=64)
    password = models.CharField(max_length=64)

Database migration

python manage.py makemigrations
python manage.py migrate

Add data to database

 

Routing urls

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),
]

View function

from django.shortcuts import render, redirect, HttpResponse
from cookie import models

def login(request):
    ret = ""
    if request.method == "POST":
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")
        # Query user name and password in database
        user_obj = models.UserInfo.objects.filter(username=user, password=pwd).first()
        if user_obj:
            """
            //If the validation passes, redirect to index and set the cookie
            """
            obj = redirect("/index/")
            obj.set_cookie("is_login", True, 30)  # cookie Valid for 30 seconds
            obj.set_cookie("username", user_obj.username)
            return obj
        else:
            ret = "Wrong user name or password"
    return render(request, "login.html", {"ret": ret})


def index(request):
    is_login = request.COOKIES.get("is_login")
    username = request.COOKIES.get("username")
    if not is_login:
        return redirect("/login/")
    return render(request, "index.html", {
        "user": username
    })    

Template page

login.html

<body>
<h3>User login page</h3>
<form action="/login/" method="post">
    {% csrf_token %}
    <p>User name:<input type="text" name="user"></p>
    <p>Password:<input type="password" name="pwd"></p>
    <p><span>{{ ret }}</span></p>
    <input type="submit" value="Sign in" class="sub_btn">
</form>
</body>

Homepage index.html

<body>
<h3>This is index Page. Hello {{ user }}</h3>
</body>

Let's visit and test

Click login

As you can see, you have jumped to the index page as expected

Let's take a look at the cookie s set up

 

Take another look at the cookie value when redirecting access

 

2 set session

Create application

python manage.py startapp session

Registration application

settings.py

INSTALLED_APPS = [
    ...
    'cookie.apps.CookieConfig',
    'session.apps.SessionConfig'
]

Routing urls

.....
from session import views as session_views

urlpatterns = [
    ......
    path('session_login', session_views.session_login),
    path('session_index', session_views.session_index),
    path('session_logout', session_views.session_logout),
]

View function

from django.shortcuts import render, redirect
from cookie import models  # Because we need data, we need to eat cookie Import in app

def session_login(request):
    ret = ""
    if request.method == "POST":
        user = request.POST.get("user")
        pwd = request.POST.get("pwd")
        user_obj = models.UserInfo.objects.filter(username=user, password=pwd).first()
        if user_obj:
            """
            //If the verification passes, set the session and return the session [index]
            """
            request.session["is_login"] = True
            request.session["username"] = user_obj.username
            obj = redirect("/session_index/")
            return obj
        else:
            ret = "Wrong user name or password"
    return render(request, "session_login.html", {"ret": ret})

 

def session_index(request):
    is_login = request.session.get("is_login")
    username = request.session.get("username")
    if not is_login:
        """If not, go to the login page"""
        return redirect("/session_login")

    return render(request, "session_index.html", {"user": username})


def session_logout(request):
    request.session.flush()
    return redirect("/session_login/")

Template page

session_index.html

<h3>Be based on session User login for</h3>
<form action="/session_login/" method="post">
    {% csrf_token %}
    <p>User name:<input type="text" name="user"></p>
    <p>Password:<input type="password" name="pwd"></p>
    <p><span>{{ ret }}</span></p>
    <input type="submit" value="Sign in" class="sub_btn">
</form>

session_index.html

<body>
<h3>This is session_index Page.</h3>
<h3>Hello {{ user }}</h3>
<a href="/session_logout/">Cancellation</a>
</body>

 

Down test

 

 

You can see that the session table in the database already has data. The session key is randomly generated, which is the cookie key carried during the request. The session data is

request.session["is_login"] = True
request.session["username"] = user_obj.username, the number encrypted by some algorithm

 

 

Let's take a look at the page

 

Posted by BlueGemini on Tue, 19 Nov 2019 08:19:28 -0800