Django project practice (mall): Third, user registration (back-end development)

Insert picture description here

(According to the content of teacher's live broadcast)

1. User registration business logic analysis

Insert picture description here

  • After the user enters the address, get the registration page
    Insert picture description here
  • The user enters a user name, and the front end should check whether the user name has been registered;
  • The two passwords must be the same, otherwise the front-end should control to re-enter
  • The front end will verify whether the mobile phone number is in compliance with the specifications
  • The graphic verification code will be verified. After it is correct, the SMS verification code should take effect.
  • Registration can only be submitted after the SMS verification code is correct
  • After all the above are correct, the backend will process the registration request
  • The registration request sends data to the backend through the form POST
  • After the registration view receives the request, it receives the data
  • Check the data, if the data is wrong or does not meet the specifications, directly return to the login interface and send an error message
  • After the data is verified correctly, save the data: save the data to the mysql database
    • Save user name, password (encrypted), mobile phone number and other information
  • Save the state to the session
    • Save the session information to redis
  • Return the registration result to the front end

2. User registration interface design and definition

1. The basic idea of ​​designing an interface

  • For the design of the interface, we must design an interface suitable for the business logic according to the specific business logic.
  • Ideas for designing the interface:

1.1 Analyze the business logic to be implemented:

  • It is clear that several related sub-businesses are involved in this business.
  • Design each sub-business as an interface.

1.2 Analyze the functional tasks of the interface, clarify the access method and return data of the interface:

  • Request method (such as GET, POST, PUT, DELETE, etc.).
  • Request address.
  • Request parameters (such as path parameters, query strings, forms, JSON, etc.).
  • Response data (such as HTML, JSON, etc.).

2. User registration interface design

  • User registration for this business may involve the following sub-businesses
    • Whether the user name has been registered
    • Is the graphic verification code correct?
    • Send mobile phone verification code
    • User registration normally
  • The following focuses on the design of the sub-service interface for normal user registration

2.1 Request method

Options Program
Request method POST
Request address /register/

2.2 Request parameters: form parameters

parameter name Types of Must pass Description
username string Yes username
password string Yes password
password2 string Yes Confirm Password
mobile string Yes phone number
sms_code string Yes SMS verification code
allow string Yes Do you agree to the user agreement

2.3 Response results

Response result Response content
registration failed Respond to error prompts
registration success Redirect to homepage

3. Implementation of user registration interface

3.1 User registration interface definition

# ./apps/users/views.py
from django.shortcuts import render
from django.views import View


class RegisterView(View):
    """用户注册"""

    def get(self,request):
        """提供用户注册页面"""
        return render(request, 'register.html')

    def post(self,request):
        """提供用户注册逻辑"""

        # 接收数据及数据校验 
        pass

3.2 Define the verification processing class

  • Define forms.py under ./apps/users to verify the data that needs to be verified
  • Perform simple verification on the data: variable name (passed parameter name) = form.CharField (simple verification type = standard value, error message dictionary)
    • User name, password, confirm password, mobile phone to verify the maximum length, minimum length, and whether it is required
    • The verification of user name and mobile phone number can be verified by ajax on the front end, and it will not be processed here
    • Graphic verification code: no verification is required. After the graphic verification code is correct, the SMS verification can be sent, otherwise the SMS verification code cannot be sent
    • SMS verification code: This film only has the length and required fields for simple verification, and there is a special verification algorithm to judge the correctness of the SMS verification code
  • Define clean(self) function, extend data verification
    • First call the clean(self) verification function of the base class itself: cleaned_data = super().clean()
    • Then judge whether the two passwords are the same,
      • If inconsistent, throw an exception
# ./apps/users/form.py
from django import forms

class RegisterForm(forms.Form):
    # 变量名:必须前端传递参数一致
    # max_length:限制最大长度
    # min_length:限制最小长度
    # required:True,必须填写
    # error_message:错误信息,字典类型,key是前面对应的限制条件,value是对应的错误信息
    username=forms.CharField(max_length=20,min_length=5,required=True,error_messages={
    
    "max_length": "用户名长度最长为20", "min_length": "用户名最少长度为5","required":"用户名必须填写"})
    password = forms.CharField(max_length=20, min_length=8, required=True,error_messages={
    
    "max_length": "密码长度最长为20", "min_length": "密码最少长度为8","required":"密码必须填写"})
    password2 = forms.CharField(max_length=20, min_length=8, required=True,error_messages={
    
    "max_length": "确认密码长度最长为20", "min_length": "确认密码最少长度为8","required":"确认密码必须填写"})
    mobile = forms.CharField(max_length=11, min_length=11, required=True,error_messages={
    
    "max_length": "手机长度最长为20", "min_length": "手机最少长度为11","required":"手机必须填写"})
    sms_code = forms.CharField(max_length=6, min_length=6, required=True,error_messages={
    
    "max_length": "手机长度最长为6", "min_length": "手机最少长度为6","required":"短信验证码必须填写"})

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get('password')
        password2 = cleaned_data.get('password2')

        if password != password2:
            raise forms.ValidationError('两次密码不一致')
        return cleaned_data

3.3 User registration interface development

  • Receive and verify parameters: instantiate the verification processing class
  • Judging the verification result
  • If the verification is correct:
    • Take out user name, password, mobile phone number
    • Save registration information to the database: use the user model class method provided by Django
    • State keep (not write temporarily)
    • Redirect back to the homepage
  • If the check is wrong:
    • Take out the check error message and generate the error message in the format to be returned
    • Return to the registration page (or home page)
from django.shortcuts import render
from django.views import View
from .forms import RegisterForm
# from .models import User
from users.models import User
from django import http


class RegisterView(View):
    """用户注册"""

    def get(self,request):
        """提供用户注册页面"""
        return render(request, 'register.html')

    def post(self,request):
        """提供用户注册逻辑"""

        # 校验参数
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            username = register_form.cleaned_data.get('username')
            password = register_form.cleaned_data.get('password')
            mobile = register_form.cleaned_data.get('mobile')

            # 保存到数据库中
            try:
                User.objects.create_user(username=username, password=password, mobile=mobile)
            except Exception as e:
                return render(request, 'register.html', {
    
    'register_errmsg': '注册失败'})

                # 状态保持

                # 响应结果
                return http.HttpResponse('注册成功, 重定向到首页')
                # return redirect(reverse('contents:index'))
            else:
                print(register_form.errors.get_json_data())
                context = {
    
    
                    'forms_errors': register_form.errors
                }
                return render(request, 'register.html', context=context)

3.4 here an exception handling

3.4.1 Description of error message:

If the following error message appearsInsert picture description here

3.4.2 Solution:

Need to check the guide package path

  • 将 from .models import User 改为 from users.models import User
  • At the same time change lgshop to Scoures Root
    Insert picture description here

Insert picture description here

3.4.3 Solution Two:

  • ./lgshop/urls.py
    Insert picture description here
    Insert picture description here

3.5 Save registration data

  • Here, use the create_user() method provided by the Django authentication system user model class to create a new user.
  • Here the create_user() method encapsulates the set_password() method to encrypt the password.
    Insert picture description here

3.6 Respond to the registration result

  • Registration is successful, redirect to the home page (the premise is to define the home page, the steps are as follows)
    • Create a homepage content application
    • Write index.html
    • Write view method
    • Register the contents application
      Insert picture description here

3.7 State maintenance

  • If the requirement is that the user login is successful after the registration is successful, then the state can be maintained after the registration is successful.
  • If the requirement is that the successful registration does not mean that the user login is successful, then there is no need to maintain the state after the successful registration at this time
  • State maintenance: Write the unique identification information (such as user ID) of the authenticated user into the cookie of the current browser and the session of the server.

3.7.1 Django's login() method (state retention)

  • The Django user authentication system provides the login() method: encapsulates the operation of writing to the session, helps us quickly log in to a user, and achieve state retention.
  • login () Location: django.contrib.auth. the init .py file.

3.7.2 State keeps the location of session data storage

  • The session is stored in the No. 1 library of the Redis database
SESSION_ENGINE = "django.contrib.sessions.backends.cache"
SESSION_CACHE_ALIAS = "session"

Insert picture description here

Three, user repeated registration verification (backend)

1. Logical analysis of user name duplication registration

  • When the user registers, after all the information is input and submitted, the user will be told that the user has been registered. This kind of user experience is not friendly
  • Therefore, after the user name input box loses focus and the simple verification is correct, the user repeats the registration verification request to the background. If the repeated verification prompts that the user name has been registered and needs to be replaced, if it is not registered, nothing will be prompted
  • This operation can use ajax for asynchronous operation to improve user experience
    Insert picture description here

2. Design and definition of user name duplicate registration interface

2.1 Request method

Options Program
Request method GET
Request address /usernames/(?P[a-zA-Z0-9_-]{5,20})/count/

2.2 Request parameters: path parameters

parameter name Types of Must pass Description
username string Yes username

2.3 Response result: JSON

Response result Response content
code status code
errmsg Error message
count Record the number of the username

3. Back-end implementation

  • The user name repeated registration is not html, just return a json.

3.1 Define the view method

  • User name duplicate registration verification should not be implemented in the user registration business, and the interface is also different, so define another UsernameCountView class in users.view.py
  • The UsernameCountView class only needs a get method
  • Just need to count how many usernames in the database, there should be only one or none
  • So, after fetching the data, just return directly
  • Note: The user base class used in the data model is the user class of django, pay attention to the method of use
    Insert picture description here
# ./apps/users/views.py
class UsernameCountView(View):
    """判断用户名是否重复注册"""

    def get(self,request,username):
        """
                :param username: 用户名
                :return: 返回用户名是否重复  JSON
                """
        try:
            count = User.objects.filter(username=username).count()
            return http.JsonResponse({
    
    'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})
        except Exception as e:
            logging.error(e)
            return http.JsonResponse({
    
    'code': RETCODE.DBERR, 'errmsg': '数据访问失败', 'count': -1})

3.2 Register routing

Insert picture description here

re_path(r"^usernames/(?P<username>[a-zA-Z0-9-_]{5,20}/count/$)", views.UsernameCountView.as_view())

Guess you like

Origin blog.csdn.net/laoluobo76/article/details/113095002