When session is enabled, the HttpRequest object passed to the view request parameter will contain a session attribute, just like a dictionary object. You can read and write the Request. session attribute from anywhere in Django, or edit and use it multiple times. www.liujiangblog.com/course/djan…

This file is at my C:\Users\17764530215\test\mysite address

1.urls.py

from django.contrib import admin
from django.urls import path
from login import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    path('login/', views.login),
    path('register/', views.register),
    path('logout/', views.logout),
]
Copy the code

Strategy:

  • If the user does not login, the login page is displayed regardless of whether the user accesses index or login and logout
  • If you have logged in, the login page is automatically redirected to the INDEX page
  • If you have logged in to the register page, you are not allowed to directly access the register page
  • After you log out, the login page is displayed

(Wow, that’s what we do!!)

2.login/models.py

from django.db import models

# Create your models here.


class User(models.Model) :

    gender = (
        ('male'."Male"),
        ('female'."Female"),
    )

    name = models.CharField(max_length=128, unique=True)
    password = models.CharField(max_length=256)
    email = models.EmailField(unique=True)
    sex = models.CharField(max_length=32, choices=gender, default="Male")
    c_time = models.DateTimeField(auto_now_add=True)

    def __str__(self) :
        return self.name

    class Meta:
        ordering = ["-c_time"]
        verbose_name = "User"
        verbose_name_plural = "User"
Copy the code

Meanings of each field:

Name: Mandatory. The value contains a maximum of 128 characters and is unique. Password: mandatory. The value contains a maximum of 256 characters. Email: Use Django’s built-in email type, which is unique. Sex: use a choice between male and female, default male; Use the __str__ method to help humanize the object information. Metadata in the definition of users by the creation time of the reverse order, that is, the most recent first display;

3. Views. The login and login. HTML

views.login:

def login(request) :
    if request.session.get('is_login'.None) :# Repeat login is not allowed
        return redirect('/index/')
    if request.method == 'POST':
        login_form = forms.UserForm(request.POST)   I filled out this form last time, so I get the data from this form here
        message = 'Please check what you have filled in! '
        if login_form.is_valid():
            username = login_form.cleaned_data.get('username')
            password = login_form.cleaned_data.get('password')

            try:
                user = models.User.objects.get(name=username)
            except :
                message = 'User does not exist! '
                return render(request, 'login/login.html'.locals())

            if user.password == password:   If both username and password are successful
                Write user status and data to session dictionary:
                request.session['is_login'] = True  #is_login=True indicates successful login
                request.session['user_id'] = user.id
                request.session['user_name'] = user.name
                return redirect('/index/')  # Redirect to home page
            else:
                message = 'Password is incorrect! '
                return render(request, 'login/login.html'.locals())
        else:
            return render(request, 'login/login.html'.locals())

    If not POST, go to login.html
    login_form = forms.UserForm()
    return render(request, 'login/login.html'.locals())

Copy the code

When we enter login, we’re going to look for the is_login entry in the session, and if it’s true we’re logged in, so we’re going to redirect to /index/ and go to the home page.

If it is False, that is, not logged in, go down. If it’s POST, it does a bunch of things. If it’s not POST, it means it’s the first time you’ve logged in to the login page using GET. Create an object login_form with forms.userForm and pass it as a parameter to the login/login.html template file, which I’ll cover later.

If it’s False, if it’s POST, it means that the form was filled in, so there’s a lot of business logic and session management involved here, so focus on that. If login_form.is_valid() is as follows: Login_form = forms.userform (request.post) and verify with the database username and password. If yes, change request.session[‘is_login’] to True. The user_id and user_name fields are also changed to the corresponding data. This should be useful later.

Let’s go to login/login.html

<! doctypehtml>
<html lang="en">
  <head>
    <! -- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <! The above meta tag * must * come first, anything else * must * follow! -->
    <! -- Bootstrap CSS -->
    <link href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
    <title>The login</title>
  </head>
  <body>
    <div class="container">
            <div class="col">
                <form class="form-login" action="/login/" method="post">
                  {% if message %}
                    <div class="alert alert-warning">{{ message }}</div>
                  {% endif %}
                  {% csrf_token %}
                  <h3 class="text-center">Welcome to login</h3>

                  {{ login_form }}

                  <div>
                      <a href="/register/" class="text-success " ><ins>New User registration</ins></a>
                      <button type="submit" class="btn btn-primary float-right">The login</button>
                  </div>
                </form>
            </div>
    </div> <! -- /container -->

    <! -- Optional JavaScript -->
    <! -- jQuery first, then Popper.js, then Bootstrap JS -->The following three references are in the same order #}<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <script src="https://cdn.bootcss.com/popper.js/1.15.0/umd/popper.js"></script>
    <script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>

  </body>
</html>
Copy the code

The important thing here is that this statement — {{login_form}}, insert a form login_form at this position, and after filling out the form, Use the login_form = forms.userform (request.POST) function in the view to retrieve the form data and verify it…

With these two, our permission management is basically complete! In essence, these two things provide a mechanism for ———— to store user data entered into the session and then pull it out of the session during validation to determine if it is a valid user. So, we just need to modify the index.html, also use session to verify, so that users accessing the url directly, because there is no session, will be blocked!

4.views.index

def index(request) :
    if not request.session.get('is_login'.None) :If you are not logged in, redirect to login
        return redirect('/login/')
    return render(request, 'login/index.html')  If you are logged in, enter the index.html template file

Copy the code

The logic here is clear: if you are not logged in, redirect to login; If in login state, redirect directly to the real login/index.html template. In this template, we can develop various functions. The demo login/index/ HTML looks like this:

<! DOCTYPEhtml>
    <! -- Optional JavaScript -->
    <! -- jQuery first, then Popper.js, then Bootstrap JS -->The following three references are in the same order #}<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <script src="https://cdn.bootcss.com/popper.js/1.15.0/umd/popper.js"></script>
    <script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script></body>
</html>
Copy the code

The important thing here is that this statement — {{login_form}}, insert a form login_form at this position, and after filling out the form, Use the login_form = forms.userform (request.POST) function in the view to retrieve the form data and verify it… With these two, our permission management is basically complete! In essence, these two things provide a mechanism for ———— to store user data entered into the session and then pull it out of the session during validation to determine if it is a valid user. So, we just need to modify the index.html, also use session to verify, so that users accessing the url directly, because there is no session, will be blocked!

4.views.index

def index(request) :
    if not request.session.get('is_login'.None) :If you are not logged in, redirect to login
        return redirect('/login/')
    return render(request, 'login/index.html')  If you are logged in, enter the index.html template fileCopy the code

The logic here is clear: if you are not logged in, redirect to login; If in login state, redirect directly to the real login/index.html template. In this template, we can develop various functions. The demo login/index/ HTML looks like this:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home page</title>
</head>
<body>
<h1>{{ request.session.user_name }}! Welcome back!</h1>
<p>
    <a href="/logout/">logout</a>
</p>
</body>https://www.liujiangblog.com/course/django/112 this file on my C: \ Users \ \ test \ mysite address 1. 17764530215 urls. Py the from django. Contrib import admin from django.urls import path from login import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index), path('login/', views.login), path('register/', views.register), path('logout/', Views.logout),] If an unlogged user accesses index, login, and logout, the login page will be automatically redirected to the index page. If the user accesses login, the login page will be automatically redirected to the index page. Therefore, the user is not allowed to directly access the Register page. Automatically jump to the login screen (wow, that's what we do!!) 2.login/models.py from django.db import models # Create your models here. class User(models.Model): Gender = (('male', 'male'), ('female', 'female'),) name = models.CharField(max_length=128, unique=True) password = models.CharField(max_length=256) email = models.EmailField(unique=True) sex = models.CharField(max_length=32, choices=gender, Default =" male ") c_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self. Name class Meta: Verbose_name = "user" verbose_name_plural = "user". Name: mandatory. It contains a maximum of 128 characters. Password: mandatory. The value contains a maximum of 256 characters. Email: Use Django's built-in email type, which is unique. Sex: use a choice between male and female, default male; Use the __str__ method to help humanize the object information. Metadata in the definition of users by the creation time of the reverse order, that is, the most recent first display; Def login(request): def login(request): if request.session.get('is_login', None): Return redirect('/index/') if request.method == 'POST': Login_form = forms.userform (request.post) # this form was filled in last time. ' if login_form.is_valid(): username = login_form.cleaned_data.get('username') password = login_form.cleaned_data.get('password') try: User = models.user.objects.get (name=username) except: message = 'user does not exist! ' return render(request, 'login/login.html', locals()) if user.password == password: Write user status and data to the session dictionary: Request. session['is_login'] =True #is_login=True Request. session['user_id'] = user.id Request. Session ['user_name'] = user.name return redirect('/index/') # else: message = 'password incorrect! ' return render(request, 'login/login.html', locals()) else: Return render(request, 'login/login.html', locals()) HTML login_form = forms.userform () return render(request, 'login/login.html', locals()) I'm going to look for the is_login entry in the session, and if it's true then I'm logged in, so I'm going to redirect to /index/ and go to the home page. If it is False, that is, not logged in, go down. If it's POST, it does a bunch of things. If it's not POST, it means it's the first time you've logged in to the login page using GET. Create an object login_form with forms.userForm and pass it as a parameter to the login/login.html template file, which I'll cover later. If it's False, if it's POST, it means that the form was filled in, so there's a lot of business logic and session management involved here, so focus on that. If login_form.is_valid() is as follows: Login_form = forms.userform (request.post) and verify with the database username and password. If yes, change request.session['is_login'] to True. The user_id and user_name fields are also changed to the corresponding data. This should be useful later. Let's go to login/login.html<! doctypehtml>
<html lang="en">
  <head>
    <! -- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <! The above meta tag * must * come first, anything else * must * follow! -->
    <! -- Bootstrap CSS -->
    <link href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
    <title>The login</title>
  </head>
  <body>
    <div class="container">
            <div class="col">
                <form class="form-login" action="/login/" method="post">
                  {% if message %}
                    <div class="alert alert-warning">{{ message }}</div>
                  {% endif %}
                  {% csrf_token %}
                  <h3 class="text-center">Welcome to login</h3>

                  {{ login_form }}

                  <div>
                      <a href="/register/" class="text-success " ><ins>New User registration</ins></a>
                      <button type="submit" class="btn btn-primary float-right">The login</button>
                  </div>
                </form>
            </div>
    </div> <! -- /container -->

    <! -- Optional JavaScript -->
    <! -- jQuery first, then Popper.js, then Bootstrap JS -->The following three references are in the same order #}<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <script src="https://cdn.bootcss.com/popper.js/1.15.0/umd/popper.js"></script>
    <script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>

  </body>
</html>The important thing here is that this statement -- {{login_form}}, insert a form login_form at this position, and after filling out the form, Use the login_form = forms.userform (request.POST) function in the view to retrieve the form data and verify it... With these two, our permission management is basically complete! In essence, these two things provide a mechanism for ———— to store user data entered into the session and then pull it out of the session during validation to determine if it is a valid user. So, we just need to modify the index.html, also use session to verify, so that users accessing the url directly, because there is no session, will be blocked!<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home page</title>
</head>
<body>
<h1>{{ request.session.user_name }}! Welcome back!</h1>
<p>
    <a href="/logout/">logout</a>
</p>
</body>
</html>
Copy the code

Displaying the user’s name + provides a hyperlink to the logout:

Finally, take a look at the implementation of logout

5.views.logout

def logout(request) :    # logout
    if not request.session.get('is_login'.None) :If you are not in the login state, it will be directly forwarded to the login screen
        # If you haven't logged in in the first place, you don't have to log out
        return redirect("/login/")

    request.session.flush() # to empty the session
    Or use the following method
    # del request.session['is_login']
    # del request.session['user_id']
    # del request.session['user_name']
    return redirect("/login/")  Redirect to the login screen
Copy the code

If you are not logged in, redirect the session to /login/. If you are logged in, flush the session with request.session.flush() before redirecting to /login/.

6. Summarize the collocation of session and Forms

  • Forms is actually in HTML, and by associating a form with an object, you can easily find what you’ve filled in through Forms.
  • Session is a powerful tool for verifying permissions! When there is no session, users can directly access the index interface. When there is a session, the processing logic of the index function becomes to determine whether to log in through the session. Of course, you must also use login,logout and other functions to maintain the session information and ensure that there is an immutability in all sessionsis_loginWhen the field is True, it is the real logged-in user.