Login and registration small case implementation (use the form form in Django to verify the user input data; the source code is attached at the end of the paper)

Login registration case

1. The first step of login and registration - create a model and generate a data table:

(1) Create in the models.py file under the app named mucis:

from django.db import models

# Create your models here.

class User(models.Model):
    username = models.CharField(max_length=30, unique=True)
    password = models.CharField(max_length=50)

(2) Execute mapping file to generate data table:


2. Construction of basic framework

(1) Login registration logout view function framework writing:

(mucis/views.py file ~)

from django.views import View			#Use class view to import!

class LoginResponse(View):
    def get(self,request):
        return "Login page"
    def post(self):
        """
        Login logic
        :return:
        """
        pass

class RegisterResponse(View):
    def get(self, request):
        return "Registration page"
    def post(self):
        """
        Registration logic
        :return:
        """
        pass
"""
WeChat official account: lonely cold
 Welcome to pay attention and continue to share dry goods articles~
If there are problems, you can also pay attention to WeChat official account!
"""
def logout(request):
    """
    Log out
    :param request:
    :return:
    """
    pass    

(2) Login and logout path configuration:

(mucis/urls.py file ~)

from django.urls import path

from mucis import views

urlpatterns = [
    path('login/', views.LoginResponse.as_view(), name="login"),   # Sign in
    path('register/', views.RegisterResponse.as_view(), name="register"),   # register
    path('logout/', views.logout, name="logout"),   # sign out
]

(2) Login registration logout front-end template framework preparation:

(templates/mucis/login.html file ~)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sign in</title>
</head>
<body>
    <form action="" method="post">
        {% csrf_token %}
        <h2>Sign in</h2>
        user name:<input type="text" name="username"><br>
        password:<input type="password" name="password"><br>
        <button type="submit">Sign in</button>
    </form>
</body>
</html>

(templates/mucis/register.html file ~)

Note as like as two peas: you can see that the registration and login pages are exactly the same. You think they will share a template directly. In real use, registration requires more information than login, so it is impossible for the two to use the same template. For the convenience of explanation, we only built a model with user name and password. Therefore, it will create the illusion that registration and login can use the same template!
If you don't believe me, I added an input box in the registration template below, but it's useless. I just want to emphasize this problem!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>register</title>
</head>
<body>
    <form action="" method="post">
        {% csrf_token %}
        <h2>register</h2>
        user name:<input type="text" name="username"><br>
        password:<input type="password" name="password"><br>

        cell-phone number:<input type="text" name="phone"><br>
        <button type="submit">register</button>
    </form>
</body>
</html>

3. Login and logout logic implementation

Briefly analyze the implementation of login registration logic. Take the implementation of login logic as an example:

Problem introduction - when writing login logic, you need to simply verify the data submitted by users in the form. Before I checked it, I used if directly in the view function. It's OK, but is there a B grid? No, so we won't do that this time!

In fact, the main reason why it is not used like that is that django provides the function of a form, which can be used to verify the legitimacy of data and generate HTML code!!!

(1) Pure theory:

① Import of form:

  • Both the login page and the registration page use the form to submit data

  • When the data is submitted to the background, the legitimacy of the data needs to be verified in the view function

  • django provides the function of a form, which can be used to verify the legitimacy of data and generate HTML code

  • So in this login registration case, we use the django's own form to generate front-end pages and validation data

② About using django form:

  1. Create a forms.py file, put it in the specified app, and then write the form in it
  2. Forms are implemented through classes, which inherit from forms.Form, and then define the fields to be verified
  3. In the form, as like as two peas, the creation field is exactly the same as the model, but there are no null=True or blank=True parameters, and some of them are required=True/False.
  4. Use is_ The valid () method can verify whether the data submitted by the user is legal, and the name of the HTML form element must be consistent with the name of the form in django, otherwise it will not match. (for example, the name attribute value of the HTML form element obtained by request.POST is the same as the name in the form: username,password)
  5. is_bound property: used to indicate whether the form is bound to data. If it is bound, it returns True; otherwise, it returns False
  6. cleaned_data: This is in is_ When valid () returns True, it saves the data submitted by the user

③ Description of some parameters in the form:

  • max_length maximum length
  • min_length minimum length
  • The widget is responsible for rendering the input elements of the HTML form on the web page and extracting the submitted raw data
  • attrs contains the HTML attributes that the rendered Widget will set
  • error_messages error messages

Note: Although form can generate front-end pages, this function is rarely used in practice, mainly using the verification function of form!

(2) In this case, this form is actually used:

Create a forms.py file under this app named mucis and write form verification (data verification of user login and registration):

from django import forms
from django.core.validators import RegexValidator     #Import the verifier to verify the phone number below



#Verify login
class LoginForm(forms.Form):
    #Length check / non empty reminder
    username = forms.CharField(max_length=16,min_length=6,error_messages=
                {"max_length":"The length cannot exceed 16 bits",
                 "min_length":"Length cannot be less than 6 bits",
                 "required":"User name cannot be empty"
                 })
    password = forms.CharField(max_length=16,min_length=6,error_messages=
                {"max_length":"The length cannot exceed 16 bits",
                 "min_length":"Length cannot be less than 6 bits",
                 "required": "Password cannot be empty"
                })

    """"
    Explain the reasons for the following notes:
    The following function clean()It is used for data verification. I wanted to write it here form In the form verification, but later when writing business logic in the view function,
    If the authentication is successful, the user needs to log in->This means that you need to set session,and session Yes request Object, which is directly available in the view function and can be used directly;
    And if here form If it is written in the form verification, it still needs to be imported. Is it unnecessary? Therefore, note here that this logic is completed in the view function!
    """
    # def clean(self):      # The data entered by the user in the front-end form is filtered above and then analyzed in combination with all the data in the background database
    #     # Verify whether the user exists in the database
    #     # 1. Get the user name and password
    #     username = self.cleaned_data.get("username")
    #     password = self.cleaned_data.get("password")
    #     # 2. Make judgment
    #     user = User.objects.filter(username=username, password=password)
    #     return user if user else None


#Verification registration
class RegisterFrom(forms.Form):
    # Length check / non empty reminder
    username = forms.CharField(max_length=16, min_length=6, error_messages=
    {"max_length": "The length cannot exceed 16 bits",
     "min_length": "Length cannot be less than 6 bits",
     "required": "User name cannot be empty"
     })
    password = forms.CharField(max_length=16, min_length=6, error_messages=
    {"max_length": "The length cannot exceed 16 bits",
     "min_length": "Length cannot be less than 6 bits",
     "required": "Password cannot be empty"
     })
    phone = forms.CharField(max_length=11, min_length=1, validators=[RegexValidator(r"^1[3-9][0-9]{9}$","Wrong mobile phone number format!")],error_messages=
    {"max_length": "Mobile phone number can only be 11 digits",
     "min_length": "Mobile phone number can only be 11 digits",
     "required": "Mobile phone number cannot be empty"
     })

(3) Perfect business logic of view function:

from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View			#Use class view to import!
from .models import User

from .forms import LoginForm, RegisterFrom


class LoginResponse(View):
    def get(self,request):
        username = request.session.get("username")
        return render(request, "mucis/login.html", context={"username":username})

    def post(self, request):
        """
        Login logic
        :return:
        """

        # Get user data
        data = request.POST
        # Check data
        # Check whether the data exists and judge the length / format
        '''
        Print observation request.POST,Its data format:
        <QueryDict: {'csrfmiddlewaretoken':['ILsinMw9...VBBR'], 'username':
        ['124134314'], 'password': ['3432423']}>
        You will find that it is a dictionary type that contains the data entered by the user. And we form Form verification needs to be performed after instantiating the passed in form
        Values are dictionary types, so they are passed in directly request.POST Just!
        '''
        form = LoginForm(data)        # Pass the obtained parameters into the RegisterForm class,
        if form.is_valid():     # Use is_ The valid () method verifies the validity of the submitted data, that is, whether it passes the form verification
            # get data
            username = form.cleaned_data.get("username")       # # Get the information cleaned by the form component and use cleaned_data gets the value of a single data object
            password = form.cleaned_data.get("password")
            # Determine whether the user exists in the database
            user = User.objects.filter(username=username, password=password).first()    # Get user instance
            if user:
                # Setting session information
                request.session["username"] = user.username
            return redirect(reverse('login'))      # Redirect to the login page and re request the login page
        else:  # Get the specific error format information in the form! [through debugging, it is found that the error information of form verification is in form.errors ~]
            error = form.errors
            err_li = []
            for e in error:  # error is a similar dictionary type. The for loop gets the key of the dictionary
                err_li.append(error.get(e).data[0].message + ",")
            return HttpResponse(err_li)


class RegisterResponse(View):
    def get(self,request):
        return render(request,"mucis/register.html")

    def post(self,request):
        """
        Registration logic
        :return:
        """
        # Get user data
        data = request.POST
        # Check data
        form = RegisterFrom(data)
        if form.is_valid():
            username = form.cleaned_data.get("username")
            password = form.cleaned_data.get("password")
            # Warehousing
            try:
                User.objects.create(username=username,password=password)
                return redirect(reverse("login"))
            except Exception as e:
                return redirect(reverse("register"))        #If an exception occurs, return to the registration page!
        else:
            error = form.errors
            err_li = []
            for e in error:     #error is a similar dictionary type. The for loop gets the key of the dictionary
                err_li.append(error.get(e).data[0].message+",")
            return HttpResponse(err_li)


def logout(request):
    """
    Log out
    :param request:
    :return:
    """
    request.session.flush()
    return redirect(reverse("login"))

(4) The login page has been slightly modified

  1. If the user has logged in, it indicates that the user has logged in successfully by displaying "welcome XXX";
  2. Add exit login option.

4. Case realization effect display:

(1) Registration function:

After clicking Register, the registration is successful and you will jump to the login page:

The observation database also has corresponding user data:

(2) Login function:

After clicking login, you will find that the login is successful!

(3) Exit function:

Click exit to log in and jump to the login interface, OK!

(4) If the data is illegal when logging in:

(5) If the data is illegal during registration:

Project source code:

Link: https://pan.baidu.com/s/18QkSulZaA3XCqiKsOE5_fA
Extraction code: GHZ6

Keywords: Python Django

Added by dare87 on Sun, 21 Nov 2021 03:56:27 +0200