前后端分离实现注册+登录(Vue3.0 + Django3.2)

前后,分离,实现,注册,登录,vue3,django3 · 浏览次数 : 86

小编点评

**1. 创建djangoproject 环境** 使用 pycharm 搭建 Django 环境,构建后端1、结构树2、settings.py\"\"\"Django settings for vueDjango project.Generated by 'django-admin startproject' using Django 3.2.For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/# **2. 创建 models.py** ```python from django.db import models class User(models.Model): username = models.CharField(max_length=32, verbose_name="用户名") passwd = models.CharField(max_length=32, verbose_name="密码") ``` **3. 创建 serializers.py** ```python from rest_framework import serializers class UserModelSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" ``` **4. 创建 views.py** ```python from rest_framework import status from .serializers import UserModelSerializer, User from django.shortcuts import render, HttpResponse, redirect from django.urls import path, reverse from .models import User @path('vue/') def VueViews(APIView): def get(self, request): instance_list = User.objects.all() serializer = UserModelSerializer(instance_list, many=True) return HttpResponse(serializer.data) def post(self, request): serializer = UserModelSerializer(data=request.data) if serializer.is_valid(): username = request.data['username'] passwd = request.data['passwd'] if request.data.get('passwd2', ''): user = User.objects.filter(username=username).first() if user.passwd == passwd: user.save() return HttpResponse(json.dumps({"state": "success"})) else: return HttpResponse(json.dumps({"state": "fail2", "tip": "两次密码输入不同,请重新输入"})) else: return HttpResponse(json.dumps({"state": "fail3", "tip": "密码错误,请重新输入"})) return HttpResponse(json.dumps({"state": "fail1", "tip": "用户已存在"})) ``` **5. 创建 settings.py** ```python # Other settings... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_database', 'USER': 'root', 'PASSWORD': 'password', } } ``` **6. 运行服务器** 运行服务器,访问 `localhost:8000/vue/`,应该看到用户的列表。

正文

博客地址:https://www.cnblogs.com/zylyehuo/

一、使用 vite+webstorm 搭建 Vue 环境,构建前端

1、结构树

2、main.js

import { createApp } from 'vue'
//import './style.css'
import App from './App.vue'

import router from "./utils/router";

createApp(App).use(router).mount('#app')

3、http.js

import axios from "axios";  // 要导入安装的包,则直接填写包名即可。不需要使用路径

// 实例化
const http = axios.create({
    //baseURL: 'http://wthrcdn.etouch.cn/',    // 请求的公共路径,一般填写服务端的默认的api地址,这个地址在具体使用的时候覆盖
    baseURL: 'http://127.0.0.1:8000/vue/',    // 请求的公共路径,一般填写服务端的默认的api地址,这个地址在具体使用的时候覆盖
    timeout: 8000,                           // 最大请求超时时间,请求超过这个时间则报错,有文件上传的站点不要设置这个参数
    //headers: {'X-Custom-Header': 'foobar'}   // 默认的预定义请求头,一般工作中这里填写隐藏了客户端身份的字段
});

export default http;

4、router.js

import {createRouter, createWebHistory} from 'vue-router';
import Login from "../views/Login.vue";
import Register from "../views/Register.vue";
import Index from "../components/Index.vue";

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: "/",
            name: "myLogin",
            component: Login,
        },
        {
            path: "/login",
            name: "Login",
            component: Login,
        },
        {
            path: "/reg",
            name: "Register",
            component: Register,
        },
        {
            path: "/index",
            name: "Index",
            component: Index,
        },
    ]
})

export default router;

5、App.vue

<script>

</script>

<template>
  <router-view></router-view>
</template>

<style scoped>

</style>

6、Index.vue

<template>
  <button><router-link to="/reg">register</router-link></button>
  <button><router-link to="/login">login</router-link></button>
  <h3 @click="log">{{ message }}</h3>
  <span>{{ login_message }}</span>
</template>


<!-- 以下为选项API格式 -->
<script>
export default {
  name: "Index",
  data() {
    return {
      message: "welcome to INDEX",
      login_message: '登录成功!!!',
    }
  },
  methods: {
    log() {
      console.log(this.message)
    },
  },
}
</script>


<style scoped>

</style>

7、Register.vue

<template>
  <hr>
  <h1>注册页面</h1>
  <hr>
  用户账号:<input type="text" v-model="username"><span>{{ info1 }}</span><br>
  设置密码:<input :type="password1" v-model="passwd1">
  <button @click="pwd1">{{ tip1 }}</button>
  <span>{{ info2 }}</span><br>
  确认密码:<input :type="password2" v-model="passwd2">
  <button @click="pwd2">{{ tip2 }}</button>
  <span>{{ info2 }}</span><br>
  <button><a href="/login" @click.prevent="send_post">register</a></button>
  <button>
    <router-link to="/login">login</router-link>
  </button>
</template>

<script>
import http from "../utils/http.js";

export default {
  name: "Register",
  data() {
    return {
      username: '请输入用户名',
      passwd1: '请输入密码',
      passwd2: '请确认密码',
      password1: 'password',
      password2: 'password',
      tip1: '显示密码',
      tip2: '显示密码',
      num1: 0,
      num2: 0,
      info1: '',
      info2: ''
    }
  },
  methods: {
    pwd1() {
      if (this.num1 === 0) {
        this.password1 = 'text'
        this.tip1 = '隐藏密码'
        this.num1 = 1
      } else {
        this.password1 = 'password'
        this.tip1 = '显示密码'
        this.num1 = 0
      }
    },
    pwd2() {
      if (this.num2 === 0) {
        this.password2 = 'text'
        this.tip2 = '隐藏密码'
        this.num2 = 1
      } else {
        this.password2 = 'password'
        this.tip2 = '显示密码'
        this.num2 = 0
      }
    },
    send_post() {
      http.post("http://127.0.0.1:8000/vue/", {
            username: this.username,
            passwd: this.passwd1,
            passwd2: this.passwd2,
          },
      ).then(response => {
        //console.log(response.data); // 服务端响应的响应体
        if (response.data.state == 'fail1') {
          //console.log('注册失败')
          this.info1 = response.data.tip
          this.info2 = ''
        } else if (response.data.state == 'fail2') {
          this.info1 = ''
          this.info2 = response.data.tip
        } else {
          window.location.href = "/login"
        }
      }).catch(error => {
        console.log('请求错误!error=', error)
      })
    },
  }
}
</script>

<style scoped>
* {
  margin: 10px;
}

span {
  color: red;
}
</style>

8、Login.vue

<template>
  <hr>
  <h1>登录页面</h1>
  <hr>
  账号:<input type="text" v-model="username"><span>{{ info3 }}</span><br>
  密码:<input :type="password" v-model="passwd">
  <button @click="pwd">{{ tip }}</button>
  <span>{{ info4 }}</span>
  <br>
  <button>
    <a href="/" @click.prevent="send_post">login</a>
  </button>
  <button>
    <router-link to="/reg">register</router-link>
  </button>
</template>

<script>
import http from "../utils/http.js";

export default {
  name: "Login",
  data() {
    return {
      username: '请输入用户名',
      passwd: '请输入密码',
      password: 'password',
      tip: '显示密码',
      num: 0,
      info3: '',
      info4: '',
    }
  },
  methods: {
    pwd() {
      if (this.num === 0) {
        this.password = 'text'
        this.tip = '隐藏密码'
        this.num = 1
      } else {
        this.password = 'password'
        this.tip = '显示密码'
        this.num = 0
      }
    },
    send_post() {
      http.post("http://127.0.0.1:8000/vue/", {
            username: this.username,
            passwd: this.passwd,
          },
      ).then(response => {
        //console.log(response.data); // 服务端响应的响应体
        if (response.data.state == 'fail3') {
          //console.log('注册失败')
          this.info3 = ''
          this.info4 = response.data.tip
        } else if (response.data.state == 'fail4') {
          this.info3 = response.data.tip
          this.info4 = ''
        } else {
          window.location.href = "/index"
        }
      }).catch(error => {
        console.log('请求错误!error=', error)
      })
    },
  }
}
</script>


<style scoped>
* {
  margin: 10px;
}

span {
  color: red;
}
</style>

二、使用 pycharm 搭建 Django 环境,构建后端

1、结构树

2、settings.py

"""
Django settings for vueDjango project.

Generated by 'django-admin startproject' using Django 3.2.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-q!0%lzaj1csl*(6olo+!h=7de5&*@tf_@r@2+=br_nvmzsump='

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders',
    'vue.apps.VueConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'vueDjango.urls'

CORS_ORIGIN_ALLOW_ALL = True

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates']
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'vueDjango.wsgi.application'

# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

3、urls.py

from django.urls import path
from vue import views

urlpatterns = [
    path('vue/', views.VueViews.as_view()),
]

4、models.py

from django.db import models


# Create your models here.
class User(models.Model):
    """学生信息"""
    username = models.CharField(max_length=32, verbose_name="用户名")
    passwd = models.CharField(max_length=32, verbose_name="密码")

    class Meta:
        db_table = "tb_user"

    def __str__(self):
        return str(self.username)

5、serializers.py

from rest_framework import serializers
from vue.models import User


class UserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = "__all__"

6、views.py

from django.shortcuts import render, HttpResponse, redirect

# Create your views here.

from rest_framework import status
from rest_framework.views import APIView
from .serializers import UserModelSerializer, User
from rest_framework.response import Response
import json


class VueViews(APIView):
    def get(self, request):
        """获取所有用户信息"""
        # 1. 从数据库中读取用户列表信息
        instance_list = User.objects.all()
        # 2. 实例化序列化器,获取序列化对象
        serializer = UserModelSerializer(instance_list, many=True)
        # 3. 使用serializer.data实现对数据进行序列化成字典
        return Response(serializer.data)

    def post(self, request):
        """添加用户信息"""
        # 1. 获取客户端提交的数据,实例化序列化器,获取序列化对象
        serializer = UserModelSerializer(data=request.data)
        # 2. 反序列化[验证数据、保存数据到数据库]
        serializer.is_valid(raise_exception=True)

        username = request.data['username']
        passwd = request.data['passwd']
        if request.data.get('passwd2', ''):
            userinfo = User.objects.filter(username=username)
            if userinfo.exists():
                # print('用户已存在')
                info = {"state": "fail1", "tip": '用户已存在'}
                return HttpResponse(json.dumps(info))
            else:
                passwd2 = request.data['passwd2']
                if passwd2 != passwd:
                    # print('两次密码输入不同,请重新输入')
                    info = {"state": "fail2", "tip": '两次密码输入不同,请重新输入'}
                    return HttpResponse(json.dumps(info))
                else:
                    serializer.save()
                    # print('注册成功')
                # print(username, passwd, passwd2)
        else:
            userinfo = User.objects.filter(username=username)
            if userinfo.exists():
                if User.objects.get(username=username).passwd == passwd:
                    # print('登录成功')
                    pass
                else:
                    # print('密码错误,请重新输入')
                    info = {"state": "fail3", "tip": '密码错误,请重新输入'}
                    return HttpResponse(json.dumps(info))
            else:
                # print('用户名不存在,请重新输入')
                info = {"state": "fail4", "tip": '用户名不存在,请重新输入'}
                return HttpResponse(json.dumps(info))
            # print(username, passwd)

        # 3. 返回新增的模型数据经过序列化提供给客户端
        return Response(serializer.data, status=status.HTTP_201_CREATED)

与前后端分离实现注册+登录(Vue3.0 + Django3.2)相似的内容:

前后端分离实现注册+登录(Vue3.0 + Django3.2)

博客地址:https://www.cnblogs.com/zylyehuo/ 一、使用 vite+webstorm 搭建 Vue 环境,构建前端 1、结构树 2、main.js import { createApp } from 'vue' //import './style.css' import

Svelte框架实现表格协同文档

本文由葡萄城技术团队于博客园原创并首发 转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具、解决方案和服务,赋能开发者。 首先,从框架搭建上,本篇示例采用当下流行的前后端分离的开发方式,前端使用npm作为脚手架搭建Svelte框架。 后端使用Java的SpringBoot作为后端框架。 首

前端如何实现将多页数据合并导出到Excel单Sheet页解决方案|内附代码

本文由葡萄城技术团队于博客园原创并首发 转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具、解决方案和服务,赋能开发者。 前端与数据展示 前后端分离是当前比较盛行的开发模式,它使项目的分工更加明确,后端负责处理、存储数据;前端负责显示数据.前端和后端开发人员通过接口进行数据的交换。因此前端

值得推荐的Blazor UI组件库

前言 本文主要是推荐一些开源、免费、实用、美观的Blazor UI组件库,提供给广大C#/.NET开发者们学习和使用(注意:排名不分先后,都是十分优秀的开源框架和项目💖)。本文中的所有框架都已经收录到适合后端程序员的前端框架GitHub Issues知识库中,假如大家有更好组件库推荐欢迎到以下Gi

前端报表如何实现无预览打印解决方案或静默打印

本文由葡萄城技术团队于博客园原创并首发 转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具、解决方案和服务,赋能开发者。 在前端开发中,除了将数据呈现后,我们往往需要为用户提供,打印,导出等能力,导出是为了存档或是二次分析,而打印则因为很多单据需要打印出来作为主要的单据来进行下一环节的票据

前端报表如何实现无预览打印解决方案或静默打印

本文由葡萄城技术团队于博客园原创并首发 转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具、解决方案和服务,赋能开发者。 在前端开发中,除了将数据呈现后,我们往往需要为用户提供,打印,导出等能力,导出是为了存档或是二次分析,而打印则因为很多单据需要打印出来作为主要的单据来进行下一环节的票据

[转帖]Linux性能优化(四)——BCC性能监控工具

一、BCC简介 1、BCC简介 BCC是一个Python库,简化了eBPF应用的开发过程,并收集了大量性能分析相关的eBPF应用。BCC为BPF开发提供了不同的前端支持,包括Python和Lua,实现了map创建、代码编译、解析、注入等操作,使开发人员只需聚焦于用C语言开发要注入的内核代码。 BCC

[转帖]python 性能优化监控工具_Linux性能优化(四)——BCC性能监控工具

一、BCC简介 1、BCC简介 BCC是一个Python库,简化了eBPF应用的开发过程,并收集了大量性能分析相关的eBPF应用。BCC为BPF开发提供了不同的前端支持,包括Python和Lua,实现了map创建、代码编译、解析、注入等操作,使开发人员只需聚焦于用C语言开发要注入的内核代码。 BCC

【转帖】Linux性能优化(四)——BCC性能监控工具

一、BCC简介 1、BCC简介 BCC是一个Python库,简化了eBPF应用的开发过程,并收集了大量性能分析相关的eBPF应用。BCC为BPF开发提供了不同的前端支持,包括Python和Lua,实现了map创建、代码编译、解析、注入等操作,使开发人员只需聚焦于用C语言开发要注入的内核代码。 BCC

【Spring】BeanPostProcessor后置处理器

BeanPostProcessor后置处理器是Spring提供的一个扩展点,可以在Bean初始化前后做一些事情,注意这里是bean的初始化,不是实例化,BeanPostProcessor是一个接口,里面提供了两个方法,分别为postProcessBeforeInitialization(初始化之前)