django框架官方地址:https://www.djangoproject.com/
vue.js 框架官方地址:https://cn.vuejs.org/
一、构建django项目 1. 创建工程文件和APP创建django_vue
django-admin startproject django_vue进入django_vue,创建虚拟环境django_vue_env
pip install virtualenv #安装 virtualenv django_vue_env激活虚拟环境,并安装django
source ./django_vue_env/bin/activate安装 django、后面用到的django-cors-headers(跨域)、requests
创建django app
python manage.py startapp app我们的目录应该是这样的,appfront为vue项目会在后面创建。
数据库我们使用默认sqlite3 即可,如需要变更可在setting.py中databases配置。
添加app到INSTALLED_APPS
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app' ]添加数据库模型,包含book_name和add_time用于记录书籍名称和添加时间。
from django.db import models # Create your models here. class Book(models.Model): book_name = models.CharField(max_length=64) add_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.book_name做数据库迁移
python manage.py makemigrations app python manage.py migrate编写views.py添加 show_books 和add_book两个api接口,通过JsonResponse将请求数据返回。
from django.shortcuts import render # Create your views here. # 需要导入相关的模块 from django.http import JsonResponse from django.views.decorators.http import require_http_methods from django.core import serializers import requests import json from .models import Book @require_http_methods(["GET"]) def add_book(request): response = {} try: book = Book(book_name=request.GET.get('book_name')) book.save() response['msg'] = 'success' response['error_num'] = 0 except Exception as e: response['msg'] = str(e) response['error_num'] = 1 return JsonResponse(response) @require_http_methods(["GET"]) def show_books(request): response = {} try: books = Book.objects.filter() response['list'] = json.loads(serializers.serialize("json", books)) response['msg'] = 'success' response['error_num'] = 0 except Exception as e: response['msg'] = str(e) response['error_num'] = 1 return JsonResponse(response)在django_vue目录下urls.py添加api路由
from django.contrib import admin from django.urls import path,include import app.urls urlpatterns = [ path('admin/', admin.site.urls), path('api/',include(app.urls)), ]在app目录下的urls.py添加视图路由
from django.urls import path,re_path # 导入 myapp 应用的 views 文件 from . import views urlpatterns = [ re_path(r'add_book$', views.add_book), re_path(r'show_books$', views.show_books) ]重启服务,通过curl命令测试api可用性,如下接口正常。
python manage.py runserver curl :8000/api/add_book?book_name=mylife {"msg": "success", "error_num": 0} curl :8000/api/show_books {"list": [ {"model": "app.book", "pk": 9, "fields": {"book_name": "mylife", "add_time": "2021-06-16T14:44:49.230Z"}}], "msg": "success", "error_num": 0}django后端大致构建完成,接下来做vue前端。
一、构建vue项目安装vue初始化命令行工具vue-cli
npm install -g vue-cli在django_vue目录下构建前端工程appfront,其中包含webpack工具。
vue-init webpack appfrontappfront目录如下
安装渲染element-ui 、vue-resource
npm install element-ui npm install vue-resource调整src/main.js如下
import Vue from 'vue' import App from './App' import router from './router' import ElementUI from 'element-ui' import VueResource from 'vue-resource' import 'element-ui/lib/theme-chalk/index.css' Vue.config.productionTip = false Vue.use(ElementUI) Vue.use(VueResource) /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })在src/component目录下新建Home.vue,包含showBooks和addBook两个方法用于api查询。
<template> <div> <el-row display="margin-top:10px"> <el-input v-model="input" placeholder="请输入书名"></el-input> <el-button type="primary" @click="addBook()">新增</el-button> </el-row> <el-row> <el-table :data="bookList" border> <el-table-column prop="id" label="编号" min-width="100"> <template scope="scope"> {{ scope.row.pk }} </template> </el-table-column> <el-table-column prop="book_name" label="书名" min-width="100"> <template scope="scope"> {{ scope.row.fields.book_name }} </template> </el-table-column> <el-table-column prop="add_time" label="添加时间" min-width="100"> <template scope="scope"> {{ scope.row.fields.add_time }} </template> </el-table-column> </el-table> </el-row> </div> </template> <script> export default { name: 'home', data () { return { input: '', bookList: [], } }, mounted: function() { this.showBooks() }, methods: { addBook(){ this.$http.get('http://139.198.114.148:8000/api/add_book?book_name=' + this.input) .then((response) => { var res = JSON.parse(response.bodyText) if (res.error_num == 0) { this.showBooks() } else { this.$message.error('新增书籍失败,请重试') console.log(res['msg']) } }) }, showBooks(){ this.$http.get('http://139.198.114.148:8000/api/show_books') .then((response) => { var res = JSON.parse(response.bodyText) console.log(res) if (res.error_num == 0) { this.bookList = res['list'] } else { this.$message.error('查询书籍失败') console.log(res['msg']) } }) } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>