Django Vue注册登录加验证

注册 

后端django

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from myapp.models import Fruit, FruitCate, User
from myapp.serializers import FruitSerializers, CateSerializers


# Create your views here.
class RegisterAPIView(APIView):
    def post(self, request):
        name = request.data.get("name")
        passwd = request.data.get("password")
        phone = request.data.get("phone")
        # 如果用户名存在响应用户名已存在 获取用户名 模型类.objects.filter(条件)
        if User.objects.filter(name=name):
            return Response({"code": 407, "msg": "用户名已被注册"})
        try:
            User.objects.create(name=name, password=passwd, phone=phone)
        except Exception as e:
            print(e)
            return Response({"code": 405, "msg": "注册失败"})

        return Response({"msg": "注册成功", "code": 200})

前端vue 

<template>
  <div>
    <h1>注册页面</h1>
    <!-- @blur="" 失去焦点 -->
    <!-- 验证文本框输入的数据是否符合要求:当鼠标移开时判断是否符合 失去焦点时间 -->
    账号:<input type="text" v-model="user.name" @blur="checkName" /><br />
    <!-- 利用插值表达式显示对应的状态 -->
    <small>{{ tip.name }}</small>
    <br />
    密码:<input type="password" v-model="user.password" @blur="checkPwd" />
    <br />
    <small>{{ tip.password }}</small>
    <br />
    手机号:<input type="text" v-model="user.phone" @blur="checkMobile" /><br />
    <small>{{ tip.phone }}</small>
    <br />
    <button @click="but">注册</button>
  </div>
</template>
<script>
import Axios from "axios";
export default {
  data() {
    return {
      user: {
        name: "",
        password: "",
        phone: "",
      },
      tip: {
        name: "",
        password: "",
        phone: "",
      },
      error_name: false,
      error_pwd: false,
      error_mobile: false,
    };
  },
  methods: {
    but() {
      // 第一种判断方法
      if (
        this.error_name == false &&
        this.error_pwd == false &&
        this.error_mobile == false
      ) {
        Axios.post("http://127.0.0.1:8000/register/", this.user)
          .then((resp) => {
            console.log(resp.data);
            // 如果code是407提示用户已存在
            if (resp.data.code == 407) {
              alert(resp.data.msg);
            } else {
              alert(resp.data.msg);
              this.$router.push("/register");
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        alert("格式不规范,请重新注册");
      }
    },
    checkName() {
      // 设定用户名规则,验证输入的用户名是否符合规范
      // 规则:js正则表达式 和python中正则类似 正则:正确的规则
      var re = /^[0-9a-zA-Z]\w{2,5}$/;
      // 验证输入的用户名是否符合规则
      // 如果不符合规则提示 用户名不符合规范
      // 如果不指明状态一直都是undefined
      if (re.test(this.user.name)) {
        // 验证成功显示符合规范
        this.tip.name = "用户名格式正确";
        this.error_name == false;
      } else {
        // 否则用户名不符合规范
        this.tip.name = "用户名格式不正确";
        this.error_name == true;
      }
    },
    checkPwd() {
      var re = /^[0-9a-zA-Z]{2,7}$/;
      if (re.test(this.user.password)) {
        this.tip.password = "密码规范";
        this.error_pwd == false;
      } else {
        this.tip.password = "密码不规范";
        this.error_pwd == true;
      }
    },
    checkMobile() {
      var re = /^1[3-9]\d{9}$/;
      if (re.test(this.user.phone)) {
        this.tip.phone = "手机号格式正确";
        this.error_mobile == false;
      } else {
        this.tip.phone = "手机号格式不正确";
        this.error_mobile == true;
      }
    },
  },
};
</script>

<style></style>
<script>
import Axios from "axios";
export default {
  data() {
    return {
      obj: {
        user: "",
        pwd: "",
        mobile: "",
      },
      info: {
        user: "",
        pwd: "",
        mobile: "",
      },
    };
  },
  methods: {
    checkName() {
      var re = /^[0-9A-Za-z]{2,5}$/;
      if (re.test(this.obj.user)) {
        this.info.user = "用户名格式规范";
        return true;
      } else {
        this.info.user = "用户名格式不规范";
        return false;
      }
    },
    checkPwd() {
      var re = /^[0-9A-Za-z]{4,8}$/;
      if (re.test(this.obj.pwd)) {
        this.info.pwd = "密码格式正确";
        return true;
      } else {
        this.info.pwd = "密码格式不对";
        return false;
      }
    },
    checkMobile() {
      var re = /^1[3-9]\d{9}$/;
      if (re.test(this.obj.mobile)) {
        this.info.mobile = "手机号格式正确";
        return true;
      } else {
        this.info.mobile = "手机号格式不对";
        return false;
      }
    },
    but() {
      // 前面加! 表示否定
      // 因为checkName()是定义的方法,调用方法时要加括号
      if (!
           (this.checkName() == true &&
            this.checkPwd() == true && 
            this.checkMobile() == true)
         ){
            alert("格式不规范,请重新填写");
            // 注册失败直接结束
            return;
          }else{
            Axios.post("http://127.0.0.1:8000/register/", this.obj)
            .then((resp) => {
              console.log(resp.data);
              // 判断状态
              if (resp.data.code == 407) {
                alert(resp.data.msg);
              } else {
                alert(resp.data.msg);
                this.$router.push("/login");
              }
            })
            .catch((err) => {
              console.log(err);
            });
         }
    },
  },
};
</script>

<style></style>

登录 

 后端django

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from myapp.models import User


class LoginAPIView(APIView):
    def post(self, request):
        name = request.data.get("name")
        passwd = request.data.get("password")
        
        # 判断获取到的登录用户是否存在 判断登录的用户名和密码是否匹配 登陆成功
        try:
            info = User.objects.get(name=name)
        except Exception as e:
            print(e)
            return Response({"code": 204, "msg": "用户名不存在"})

        if passwd != info.password:
            return Response({"code": 205, "msg": "密码错误"})

        return Response({"code": 200, "msg": "登陆成功"})

 前端vue 

<template>
  <div>
    <div>
      <h1>登录页面</h1>
      账号:<input type="text" v-model="name" /><br /><br />
      密码:<input type="password" v-model="password" /><br /><br />
      <button @click="but">登录</button>
    </div>
  </div>
</template>

<script>
import Axios from "axios";
export default {
  data() {
    return {
      name: "",
      password: "",
    };
  },
  methods: {
    but() {
      Axios.post("http://127.0.0.1:8000/login/",{
        name: this.name,
        password: this.password,
      })
        .then((resp) => {
          console.log(resp.data);
          if (resp.data.code == 204){
            alert(resp.data.msg)
          }else if(resp.data.code == 205){
            alert(resp.data.msg)
          }else{
            alert(resp.data.msg)
            this.$router.push("/cate")
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
};
</script>

<style></style>

两者相关的路由配置

后端

from django.urls import path
from myapp import views

urlpatterns = [
    path("register/", views.RegisterAPIView.as_view()),
    path("login/", views.LoginAPIView.as_view()),
    path("cates/", views.CateViewSet.as_view({"get": "list"})),
    path("cates/<int:pk>/", views.CateViewSet.as_view({"get": "retrieve"}))
]
# 1.导包--模型视图集路由写法
from rest_framework import routers

# 2.实例化路由对象  变量名 = routers.生成路由的方式
r1 = routers.DefaultRouter()  # 默认生成带有根路径的路由
# r1 = routers.SimpleRouter()  # 直接生成路由
# 3.注册生成路由--"路由名","对应的参数"
r1.register("fruits", views.FruitView)
# 4.添加路由
urlpatterns += r1.urls

前端 

import RegisterView from '@/views/RegisterView.vue'
import LoginView from '@/views/LoginView.vue'

const routes = [
  {
    path: '/register',
    name: 'RegisterView',
    component: RegisterView
  },
  {
    path: '/login',
    name: 'LoginView',
    component: LoginView
  },
]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值