前端
<button @click="toRegister" v-if="target==2">注册</button>
//LoginBox.vue
// 注册
toRegister() {
let username = this.username
let password = this.password
let password2 = this.password2
console.log(username, password, password2)
if (username.length > 0 && password.length > 0 && password2.length > 0) {
if (password != password2) {
alert('密码两次输入不同')
} else {
axios({
url: "http://127.0.0.1:9000/register/",
type: 'json',
data: Qs.stringify({
username,
password,
password2,
}),
method: 'post',
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then((res) => {
console.log(res);
switch(res.data){
case 'same':
alert('存在同名用户')
break
default:
break
}
})
}
}else{
alert('缺少必填项')
}
}
后端
逻辑阐述
获取前端页面输入的值,并与数据库中的数据进行比较,若存在则提示用户已经存在,若不存在,则执行注册操作
# urls.py
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from myblog import views, api
# 提供用户访问的路由
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index),
path('classes/', views.classes),
path('get-menu-list/', api.getMenuList),
path('get-user-list/', api.getUserList),
# api接口
path('api/', api.api_test),
# 用户登录
path('login/', api.toLogin),
# 用户注册
path('register/', api.toRegister),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
# api.py
from django.contrib.auth.hashers import check_password, make_password
from django.contrib.auth.models import User
@api_view(['POST'])
def toRegister(request):
username = request.POST['username']
password = request.POST['password']
password2 = request.POST['password2']
print(username, password, password2)
# 判断用户是否存在
user = User.objects.filter(username=username)
if user:
# 如果已经存在
return Response('same')
else:
# 执行注册操作
newPwd = make_password(password, username)
newUser = User(username=username, password=newPwd)
newUser.save()
return Response('OK')