当前位置:网站首页>Implementation of registration function
Implementation of registration function
2022-07-27 08:32:00 【pink_ Pig___】
Run front end projects
Enter the root directory of the foreground project
Then install the dependencies
In the front-end project root directory cmd Command box installation
npm install
Start project
npm run serve
User table design
Preparation for creating tables
stay diango In the project settings.py Configuration in file mysql Database related information
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST':"localhost",
"PORT":3306, # Port number
'USER':'root',
'PASSWORD':' Database password ',
'NAME':' Database name '
}
}
And then in _init_ File installation database
import pymysql
pymysql.install_as_MySQLdb()
stay diango In the sub application of the project models.py Write the model class in the file
User table : user name 、 password 、 cell-phone number
from django.db import models
# Create your models here.
class User(models.Model):
username=models.CharField(max_length=32,unique=True,verbose_name=' user name ')
password=models.CharField(max_length=32,verbose_name=' password ')
mobile=models.CharField(max_length=16,verbose_name=' cell-phone number ')
class Meta:
verbose_name=' User table '
verbose_name_plural=verbose_name
def __str__(self):
return "%s (%s)"%(self.username,self.mobile)
Generate migration file
python manage.py makemigrations
Migration
python manage.py migrate
Write view classes
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from users.models import User
from django.http import HttpResponse
import re,random
# Create your views here.
# Check the length of user name , Whether to repeat
class CheckUsernameview(APIView):
def get(self,request,username):
if not username:
return Response({
'code':400,
'msg':' User name error '
})
if not (6<= len(username) <=32):
return Response({
'code': 400,
'msg': ' User length does not match '
})
user_count = User.objects.filter(username=username).count()
if user_count:
#user_count Not for 0, The landmark database has this data
return Response({
'code':400,
'msg':' User name already exists '
})
return Response({
'code':200,
'msg':' User name available '
})
# Check whether the mobile phone number meets the standard , repeat
class CheckMobile(APIView):
def get(self,request,mobile):
rule=r'^1[3-9][0-9]{9}$' # Define the regular mobile number
rs =re.findall(rule,mobile) # The result is a list If it doesn't match An empty list is returned
if not rs:
return Response({
'code':400,
'msg':' The mobile number format is wrong '
})
# When the program comes to this step, it shows that the format of mobile phone number is ok
mobile_count=User.objects.filter(mobile=mobile).count()
if mobile_count:
return Response({
'code':400,
'msg':' Cell phone number already exists '
})
return Response({
'code':200,
'msg':' Mobile number available '
})
# Check whether the password meets the standard
class Checkpassword(APIView):
def post(self,request):
pwd=request.data.get('pwd') # Receive the password from the front desk
# Verify password length
if not (6<=len(pwd)<=32):
return Response({
'code':400,
'msg':' Password length does not match '
})
return Response({
'code':200,
'msg':' The password is available '
})
# Check to enter the password again
class CheckPasswordReview(APIView):
def post(self,request):
pwd=request.data.get('pwd')
pwd_re=request.data.get('pwd_re')
if pwd!=pwd_re:
return Response({
'code':400,
'msg':' Password inconsistency '
})
return Response({
'code':200,
'msg':' The password is the same '
})
# Generate captcha image , And save the verification code to redis database
class Verimageview(APIView):
def get(self,request,uuid):
#1. Generate the string produced by the verification code
code=str(random.randint(1000,9999))
# According to the string into a picture # Install at the project terminal pip install captcha
from captcha.image import ImageCaptcha # Guide pack
img=ImageCaptcha() # Instantiate the class of the verification code
img_pic=img.generate(code) # The generator generates a verification code image
print(' Generated image ',img_pic) # Return is a IO Byte stream
# Save the CAPTCHA to redis
import redis # Guide pack
r=redis.Redis(host='127.0.0.1',port=6379,password='redis Library password ')
r.set(uuid,code,ex=60*5) # entry-into-force time 5 minute
print(uuid)
print(code)
# return Response(img_pic)
return HttpResponse(img_pic,content_type='image/png')
# The class that enters the verification code attempts
class CheckCodeView(APIView):
def post(self,request):
code=request.data.get('code') # The user enters the verification code
uuid=request.data.get('uuid') # User unique logo
#1, Linked database , Take out uuid The corresponding verification code
import redis # Guide pack
r=redis.Redis(host='127.0.0.1',port=6379,password='redis Library password ')
sys_code=r.get(uuid)
# If uuid If the corresponding data is empty , Description verification code has expired
if not sys_code:
return Response({
'code':400,
'msg':' The verification password has expired '
})
# Return the database to byte Data of type , Convert to string type
sys_code_str=sys_code.decode()
#2. The verification code entered by the user is compared with the verification code of the database
if sys_code_str!=code:
# If it's not consistent , Verification code error
return Response({
'code':400,
'msg':' Verification code error '
})
# If the same , Explain that the verification code passed
return Response({
'code':200,
'msg':' Verification passed '
})
# The registered class tried
class RegView(APIView):
def post(self,request):
username=request.data.get('username')
password=request.data.get('password')
mobile=request.data.get('mobile')
agree=request.data.get('agree')
# Judge whether the user has checked the agreement
if not int(agree): # turn int Because the zero of the string cannot be used not Seek judgment
return Response({
'code':400,
'msg':' The agreement is not checked '
})
if not username or not password or not mobile:
return Response({
'code':400,
'msg':' Wrong parameter input '
})
# TOOO Research user name , Password mobile number
# The calibration is finished Write to database
try:
User.objects.create(
username=username,
password=password,
mobile=mobile
)
return Response({
'code':200,
'msg':' Registered successfully '
})
except Exception as a:
return Response({
'code':400,
'msg':' Registration failed '
})
Configure the routing
Routing distribution
Create a file with the same name in the sub application for distribution
from django.contrib import admin
from django.urls import path,include
from users import urls
urlpatterns = [
path('admin/', admin.site.urls),
path('user/',include(urls)),
]
Configure the routing
# from django.contrib import admin
from django.urls import path
from users import views
urlpatterns = [
# path('admin/', admin.site.urls),
path('cher/username/<str:username>/',views.CheckUsernameview.as_view()),
path('check/mobile/<str:mobile>/',views.CheckMobile.as_view()),
path('check/password/',views.Checkpassword.as_view()),
path('check/password_re/',views.CheckPasswordReview.as_view()),
path('check/image/<str:uuid>/',views.Verimageview.as_view()),
path('check/img/code/',views.CheckCodeView.as_view()),
path('reg/',views.RegView.as_view())
]
Use after the route is configured ApiPost To check whether the interface is successful
front end
1. First install in the front-end project npm install
Then find the registration related vue file
Conduct joint commissioning of relevant functions
data(){
// Verification method of user name
let validateName = (rule, value, callback) => {
console.log(" Verify username , The rules ", rule, " user name ", value, " Callback function ", callback)
// TODO Verify username
// Failure return callback(new Error(" Beginning of letter , length 5-16 Between , Allow alphanumeric underscores "));
// success return callback();
if (!value){
return
}
this.$axios.get("/user/cher/username/"+value+'/').then(res=>{
if (res.data.code==200){
return callback()
}else{
return callback(new Error(res.data.msg))
}
}).catch(err=>{
console.log(err)
alert(' Wrong report ')
})
};
// Verification method of mobile phone number
let validateMobile = (rule, value, callback) => {
console.log(" Check cell phone number , The rules ", rule, " cell-phone number ", value, " Callback function ", callback)
// TODO Check cell phone number
// Failure return callback(new Error(" Beginning of letter , length 5-16 Between , Allow alphanumeric underscores "));
// success return callback();
if (!value){
return
}
this.$axios.get("/user/check/mobile/"+value+'/').then((result) => {
if (result.data.code==200){
return callback();
}else{
return callback(new Error(result.data.msg));
}
}).catch((err) => {
console.log(err)
alert(' The mobile number reports an error ')
});
};
// Verification method of password
let validatePass = (rule, value, callback) => {
console.log(" Check the password , The rules ", rule, " password ", value, " Callback function ", callback)
// TODO Check the password
// Failure return callback(new Error(" Beginning of letter , length 5-16 Between , Allow alphanumeric underscores "));
// success return callback();
if (!value){
return
}
this.$axios.post('/user/check/password/',{
'pwd':value}).then((result) => {
if (result.data.code==200){
return callback();
}else{
return callback(new Error(result.data.msg));
}
}).catch((err) => {
console.log(err)
alert(' Password error ')
});
};
// Confirm the verification method of password
let validateConfirmPass = (rule, value, callback) => {
console.log(" Verify the confirmation password , The rules ", rule, " Second input password ", value, " Callback function ", callback)
// TODO Verify the confirmation password
// Failure return callback(new Error(" Beginning of letter , length 5-16 Between , Allow alphanumeric underscores "));
// success return callback();
this.$axios.post('/user/check/password_re/',{
'pwd':this.RegisterUser.pass,
'pwd_re':value,
}).then((result) => {
if (result.data.code==200){
return callback()
}else{
return callback(new Error(result.data.msg));
}
})
};
// Check the picture verification code
let validateImageCode = (rule, value, callback) => {
console.log(" Verification code , The rules ", rule, " 2. Verification code ", value, " Callback function ", callback)
// TODO Verification code
// Failure return callback(new Error(" Beginning of letter , length 5-16 Between , Allow alphanumeric underscores "));
// success return callback();
this.$axios.post('/user/check/img/code/',{
'uuid':this.imageCodeID,
'code':value,
}).then((result) => {
if(result.data.code==200){
return callback()
}else{
return callback(new Error(result.data.msg))
}
}).catch((err) => {
console.log(err)
alert(' Validation error ')
});
},
methods: {
// Generate image verification code address
genImageCode() {
// Generate a uuid
this.imageCodeID = uuid4() //uuid Understood as random string , It's used to mark who you are
console.log(this.imageCodeID)
// Generate a picture verification code address /////// Modify the route of the image generated by the backend /////
this.iamgeCodeUrl = "/user/check/image/" + this.imageCodeID + "/"
console.log(this.iamgeCodeUrl)
},
// User registration
Register() {
// Whether to agree with the user agreement
if (!this.aggree) {
this.flag = true
return
}
// Checked , Then the prompt message will not be displayed
this.flag = false
// adopt element Custom form validation rules , Verify the user information entered by the user
this.$refs["ruleForm"].validate((valid) => {
if (valid) {
// TODO Registered users
this.$axios.post('/user/reg/',{
username:this.RegisterUser.name,
password:this.RegisterUser.pass,
mobile:this.RegisterUser.mobile,
agree:this.aggree,
}).then((result) => {
if (result.data.code==200){
// alert(' Registered successfully ')
// Clear the registration input
this.RegisterUser.name=''
this.RegisterUser.pass=''
this.RegisterUser.mobile=''
this.RegisterUser.confirmPass=''
this.RegisterUser.imageCode=''
this.aggree=false
// Close the pop-up window
this.isRegister=false
this.notifySucceed(result.data.msg)
}else{
// alert(' Registration failed ')
this.notifyError(result.data.msg)
}
}).catch((err) => {
console.log(err)
alert(' Wrong page ')
});
} else {
return false;
}
});
},
},
边栏推荐
- Realization of specification management and specification option management functions
- 面试官:什么是脚手架?为什么需要脚手架?常用的脚手架有哪些?
- sql_ Mode strict mode (ansi/traditional/strict_trans_tables)
- UVM入门实验1
- VS Code中#include报错(新建的头文件)
- [uni app advanced practice] take you hand-in-hand to learn the development of a purely practical complex project 1/100
- Virtual machine cloning
- Idea remote debugging
- UVM Introduction Experiment 1
- Use of "PHP Basics" Boolean
猜你喜欢

Alibaba cloud international receipt message introduction and configuration process

ERP production operation control Huaxia
![[NPUCTF2020]ReadlezPHP 1](/img/d9/590446b45f917be3f077a9ea739c20.png)
[NPUCTF2020]ReadlezPHP 1

Attack and defense World Lottery

Have a good laugh

Background image related applications - full, adaptive

Vertical align cannot align the picture and text vertically

I drew a Gu ailing with characters!

Oppo self-developed large-scale knowledge map and its application in digital intelligence engineering

Vcenter7.0 managing esxi7.0 hosts
随机推荐
Virtual machine cloning
Iterators and generators
[target detection] yolov6 theoretical interpretation + practical test visdrone data set
idea远程调试
It's better to be full than delicious; It's better to be drunk than drunk
Breadth first search
while Loop
信息化项目风险控制与应用
Use of "PHP Basics" Boolean
Dirsearch[directory scanning tool]
[geek challenge 2019] finalsql 1
pytorch_demo1
Netdata 性能监测工具介绍、安装、使用
Idea remote debugging
Use of "PHP Basics" delimiters
OPPO 自研大规模知识图谱及其在数智工程中的应用
Use of string type "PHP Basics"
Database startup report error_ user_ connect_ times &gt; 0 error
Background image related applications - full, adaptive
无法获取下列许可SOLIDWORKS Standard,无法找到使用许可文件。(-1,359,2)。