Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
1. Log-in, registration and logout logic implementation
Simple analysis of logon registration logic implementation, take logon logic implementation as an example to tell a question:
Introduction of the problem – when writing the logon logic, you need to perform a simple validation of the data submitted by the user in the form. I’ve been checking it out in the past by using if directly in the view function, which is fine, but is there a B bar? No, that’s why we’re not doing it this time!
The main reason not to use it that way is that Django provides a form function that can be used to validate data and generate HTML code!!
(1) Theoretically speaking, form form:
① The introduction of forms:
-
Both the login and registration pages use the form form to submit data
-
When the data is submitted to the background, it needs to be validated in the view function.
-
Django provides a form function that can be used to validate data and generate HTML code
-
So in this case, we’ll use the Django form to generate the front end page and validate the data.
Using Django Forms
- Create a forms.py file, place it in the specified app, and write the form in it.
- Forms are implemented through classes that inherit from Forms.form and define fields to validate.
- In the form, creating fields is exactly the same as in the model, except that there are no null=True or blank=True parameters, and only required=True/False parameters.
- The is_Valid () method validates that the data submitted by the user is valid, and that the HTML form element name must match the name of the django form, or it won’t match. (For example, in this case, the name attribute value of the HTML form element obtained by Request.post is the same as that of the form Name is the same: username,password)
- Is_bound property: Used to indicate whether the form is bound to data, returning True if it is, False otherwise.
- Cleaned_data: This saves data submitted by the user when is_VALID () returns True.
③ Some parameters in the form:
- Max_length Indicates the 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 raw data submitted
- Attrs contains HTML attributes that will be set for the rendered Widget
- Error_messages Error message
Note: Although forms can generate front-end pages, this feature is rarely used, mainly using the form validation function!
(2) Use this form in this case:
Create the forms.py file in this app named mucis and write the form validation (data validation for user login and registration) :
from django import forms
from django.core.validators import RegexValidator Import a validator to verify the phone number below
Verify login
class LoginForm(forms.Form) :
# Length check/non-null reminder
username = forms.CharField(max_length=16,min_length=6,error_messages=
{"max_length":"No longer than 16 bits."."min_length":"No less than 6 digits in length."."required":"User name cannot be empty"
})
password = forms.CharField(max_length=16,min_length=6,error_messages=
{"max_length":"No longer than 16 bits."."min_length":"No less than 6 digits in length."."required": "Password cannot be empty."
})
"""" explain the reasons for the following comments: The following function clean() is used for data validation. I was going to write it in the form validation as well, but when I write the business logic in the view function, I find that if the validation succeeds, the user needs to log in -> this means that session needs to be set, and session is set through the request object. It's directly in the view function, you can use it directly; If you want to check the form, you need to import it. "" "
# def clean(self)
Check 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. Judge
# user = User.objects.filter(username=username, password=password)
# return user if user else None
# check registration
class RegisterFrom(forms.Form) :
# Length check/non-null reminder
username = forms.CharField(max_length=16, min_length=6, error_messages=
{"max_length": "No longer than 16 bits."."min_length": "No less than 6 digits in length."."required": "User name cannot be empty"
})
password = forms.CharField(max_length=16, min_length=6, error_messages=
{"max_length": "No longer than 16 bits."."min_length": "No less than 6 digits in length."."required": "Password cannot be empty."
})
phone = forms.CharField(max_length=11, min_length=1, validators=[RegexValidator(r"^1[3-9][0-9]{9}$"."Wrong phone number format!")],error_messages=
{"max_length": "Cell phone number can only be 11 digits."."min_length": "Cell phone number can only be 11 digits."."required": "Cell phone number cannot be empty."
})
Copy the code
(3) Perfect view function business logic:
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View Use class view, 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) :
Logon logic :return: """
Get user data
data = request.POST
# Check data
Check whether the data exists, determine the length/format
Print observation Request. POST, whose data format is:
will find that it is a dictionary type that contains the data entered by the user. The form validates that the value passed in to the instantiation is a dictionary type, so just pass request.POST! ' ' '
form = LoginForm(data) Pass the obtained parameters to the RegisterForm class.
if form.is_valid(): The is_valid() method is used to validate the submitted data
# Fetch data
username = form.cleaned_data.get("username") Fetch individual data object values using cleaned_data
password = form.cleaned_data.get("password")
Check whether the user exists in the database
user = User.objects.filter(username=username, password=password).first() Get the user instance
if user:
Set session information
request.session["username"] = user.username
return redirect(reverse('login')) Redirect to the login page and re-request the login page
else: Get information about the specific formatting error in the form! Error message of form validation is found in form.errors.
error = form.errors
err_li = []
for e in error: # error is a dictionary-like type. The for loop gets the keys 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")
# put in storage
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 dictionary-like type. The for loop gets the keys 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"))
Copy the code
(4) The login page is slightly modified
- If you have logged in, welcome XXX is displayed to indicate that the login is successful.
- Added the option to log out.
2. Case implementation effect Demonstration:
(1) Registration function:
Click registration, registration is successful, jump to the login page:
Look at the database, also have the corresponding user data:
(2) Login function
Click login, you will find that login is successful!
(3) Exit function:
Click exit login, jump to login interface, OK!
(4) If the data is illegal during login:
(5) If the data is illegal at the time of registration:
Project source code:
Links:Pan.baidu.com/s/18QkSulZa…Extraction code: GHZ6
🔆 In The End!
Start now, stick to it, a little progress a day, in the near future, you will thank you for your efforts! |
---|
This blogger will continue to update the basic column of crawler and crawler combat column, carefully read this article friends, you can like the collection and comment on your feelings after reading. And can follow this blogger, read more crawler in the days ahead!
If there are mistakes or inappropriate words can be pointed out in the comment area, thank you! If reprint this article please contact me for my consent, and mark the source and the name of the blogger, thank you!