Knowledge Review
python knowledge points
- Routing Regular Matching
path('check/username/<str:username>/', CheckUsername.as_view())
- Group Naming Match
In [2]: import re In [3]: a = re.match(r'[a-zA-Z]*(?P<num>\d+)[a-zA-Z]*$', 'sad131231dasda') In [4]: a.group('num') Out[4]: '131231'
- Model Class Query
Today's explanation
User registration
According to the user registration effect map, extract the user model class field, further analyze the registration logic, and complete the main functions.
User Registration Page Effect Map
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-xtlHvHnB-1643988983822)(images/image-20210110115947667.png)]
function
Registration logic
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-18XNr5Fb-1643988983823) (images/image-20210130946870.png)]
- To generate a page's picture verification code, the method requires two triggers: auto-execution, click-execution
- Get input user name
- Verify the validity of user names using rules
- When the username regular check passes, send a request to the back end to verify that the username is duplicated
- Get Password
- Verify the legality of passwords using regularity
- Get Confirmation Password
- Verify that the password and password are identical
- Get your mobile number
- Verify the Legality of Mobile Number by Regular
- When the regular check of the mobile number passes, send a request to the back end to check if the mobile number is duplicated
- Get the authentication code entered by the user
- Check if the verification code exists
- Check whether a check box is selected
- Click the Register button to submit the information to the backend
[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-VX2BF3SE-1643988983823)(images/image-20210305161043029.png)]
User table design
User Table: User Name, Password, Mobile Number, Mailbox
You can customize the model classes, including these fields, so in real project development, you don't override them yourself; you do
Inherits django's built-in user model class: AbstractUser, overrides its own fields, but requires settings. Current user model class specified in PY
from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class User(AbstractUser): mobile = models.CharField(max_length=11, verbose_name='Cell-phone number') class Meta: db_table = 'tb_user' verbose_name = 'user' verbose_name_plural = verbose_name def __str__(self): return self.username
If you override django's built-in user model class, you must specify the current user model class in django's configuration file
# Specify User Model Class AUTH_USER_MODEL = 'user.User' # app name. User name model class name, not fixed
Once the user model class is complete, you need to migrate the generated tables before running the project
User name duplication check
API design
# User name delivery problem?? GET check/username/xxxx/
django
- First get the parameters in the path through route matching: username
- In the view, query according to the user name to get the corresponding number of users
- Return results
view
from rest_framework.views import APIView from rest_framework.response import Response from user.models import * # Create your views here. class CheckUsernameAPIView(APIView): def get(self, request, username): """ 1. User name format is incorrect, return 404 2. User name format is correct, user name is duplicated, return 400 3. User name is formatted correctly, is not duplicated, returns 200 """ # 1. Query the number of users based on their name n = User.objects.filter(username=username).count() # 2. Return results if n == 0: return Response({'msg': 'OK'}) else: return Response({'msg': 'FAIL'}, status=400)
Route
from django.urls import path, re_path from user.views import * urlpatterns = [ re_path(r'check/username/(?P<username>[a-zA-Z]\w{5,19})/', CheckUsernameAPIView.as_view()) ]
Create a superuser just to test for duplicate user names next
$ python manage.py createsuperuser # Create Super User Username: admin1 # enter one user name Email address: lsf@163.com # Enter Mailbox Password: # Enter password, not visible Password (again): # Enter confirmation password, not visible, must match previous This password is too short. It must contain at least 8 characters. # Passwords are too common and unsafe This password is too common. This password is entirely numeric. Bypass password validation and create user anyway? [y/N]: y # Whether to continue using the password Superuser created successfully.
Vue
You want to use the template in the Vue and keep the style
- Copy label elements from the template to the template of the Vue component first
- Clear app. Default Style in Vue
- In main.js Import css Style File
User Name Check
- User enters user name in text box
- Use v-mdoel directive to get user name
- After the user input is complete, the out-of-focus event (blur) is triggered, and the method for verifying the user name is performed
- In Methods
- First use js to check the username regularly, and first flag username_if there is a problem Flag sets true and sets the error message username_ Er is set to enter a 6-20 character user name, ending directly
- If the first step is OK, you need to send the username to django for duplication checking. If the status code returned is 400, you need to mark username_flag sets true and sets the error message username_err set to user name registered
<li> <label>User name:</label> <!-- blur: Is a defocus event --> <input type="text" name="user_name" id="user_name" v-model="username" @blur="check_username"> <span class="error_tip" v-show="username_flag">{{ username_err }}</span> </li> export default { name: "Register", data() { return { username_flag: false, // Flag whether to display error information, false does not display error information, true displays username: '', // User name entered by the user username_err: '' // Error message displayed } }, methods: { check_username() { // 1. js determines if the user name is legal let reg = /^[a-zA-Z]\w{5,19}$/ if (reg.test(this.username) === false) { this.username_flag = true // Regular matching of user names failed. Error information needs to be displayed this.username_err = 'Please enter 6-20 A user name of 1 character' return } else { this.username_flag = false } // 2. When js judges that the user name is legal, it sends the user name to django to determine if the user name is duplicated console.log(this.username) this.$axios.get('check/username/' + this.username + '/') .then(resp => { console.log(resp.data) this.username_flag = false // Do not display error information }) .catch(err => { console.log(err.response.data) this.username_flag = true // Error information needs to be displayed this.username_err = 'User name registered' }) } } } </script>
Duplication check of mobile number
API design
# User name delivery problem?? GET check/mobile/xxxx/
django
view
class CheckMobileAPIView(APIView): def get(self, request, mobile): """ 1. Incorrect mobile number format, return 404 2. Duplicate mobile number, return 400 3. The mobile number is formatted correctly and is not repeated. Return 200 """ # 1. Query the number of users based on their name n = User.objects.filter(mobile=mobile).count() # 2. Return results if n == 0: return Response({'msg': 'OK'}) else: return Response({'msg': 'FAIL'}, status=400)
Route
from django.urls import path, re_path from user.views import * urlpatterns = [ re_path(r'check/mobile/(?P<mobile>1[3-9]\d{9})/', CheckMobileAPIView.as_view()) ]
Vue
- User enters mobile number in text box
- Use v-mdoel command to get mobile number
- After user input is complete, trigger the out-of-focus event (blur) to perform the method of checking the phone number
- In Methods
- First use js to check the phone number regularly. If there is a problem, first mark mobile_flag sets true, and error message mobile_ Er set to enter 11-digit mobile number, end directly
- If the first step is OK, you need to send the mobile number to django for duplication check. If the status code returned is 400, you need to mark mobile_flag sets true, and error message mobile_ Er set to mobile number registered
<li> <label>Cell-phone number:</label> <input type="text" name="phone" id="phone" v-model="mobile" @blur="check_mobile"> <span class="error_tip" v-show="mobile_flag">{{ mobile_err }}</span> </li> <script> export default { name: "Register", data() { return { mobile_flag: false, // Flag whether to display error message of mobile number, false does not display error message, true displays mobile: '', // Mobile number entered on behalf of user mobile_err: '', // Error message displaying mobile number } }, methods: { check_mobile() { // 1. js Verify Mobile Number let reg = /^1[3-9]\d{9}$/ if (reg.test(this.mobile) === false) { this.mobile_flag = true // Set flag bit true to display error information this.mobile_err = 'Please enter an 11-digit mobile number' return } else { this.mobile_flag = false } // 2. Send your mobile number to django this.$axios.get('check/mobile/' + this.mobile + '/') .then(resp => { this.mobile_flag = false // Verification succeeded without error message }) .catch(err => { this.mobile_flag = true // Check failed, error message displayed this.mobile_err = 'Mobile number registered' }) } } } </script>
task
- Create a django project for cross-domain configuration
- Create a Vue project to implement axios default configuration
- Implement User Name Test Interface, User Name Repetition Check and Legality Check (consisting of letters and numbers, 5-20 bits)
- Implement the test interface of mobile phone number, realize the validity and repetition check of mobile phone number
- Implement Mailbox Test Interface
- Implement mailbox validity check: User name is composed of letters and numbers, 5-20 digits, mailbox can only be sina, qq, 163 mailboxes, such as lixianfeng@163.com
- Implement Mailbox Duplication Check
- Implement user registration page: user name, mobile number, mailbox
- When the user has finished entering the user name, test that the user name is valid and duplicated
- When the user enters the completed mobile number, immediately test whether it is legal and duplicated
- When user input is complete, test the validity and duplication of the mailbox immediately
Examination Enhancement
All of the following functions are implemented using drf + Vue
- Create a goods application
- Create Model Class
- Brand: Brand name
- Commodity: Name, price, brand (foreign key)
- Implement brand addition
- To add goods, use drop-down boxes for foreign keys
- Show all brands on the first page
- Click on the brand to jump to the list page of goods corresponding to the brand
- Show all products of the brand on the list page
- Click on the item and jump to the item details page to show the details of the item