本文用于学习django+vue.js实现web前后端分离协作开发。以一个添加和删除数据库书籍应用为实例。
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 http://127.0.0.1:8000/api/add_book?book_name=mylife
{"msg": "success", "error_num": 0}
curl http://127.0.0.1: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 appfront
appfront目录如下
安装渲染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 class="home">
<el-row display="margin-top:10px">
<el-input v-model="input" placeholder="请输入书名" style="display:inline-table; width: 30%; float:left"></el-input>
<el-button type="primary" @click="addBook()" style="float:left; margin: 2px;">新增</el-button>
</el-row>
<el-row>
<el-table :data="bookList" style="width: 100%" 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>
我们通过django-cors-headers处理跨域问题
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app',
'corsheaders', //添加app
]
添加中间件corsheaders.middleware.CorsMiddleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
在setting.py中配置跨域规则
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)
npm run dev
启动node服务器
通过npm run build
打包前端到dist目录,用于后续django链接。
三、django链接到前端
调整django_vue目录下路由urls.py如下
from django.contrib import admin
from django.urls import path,include
from django.views.generic import TemplateView //导入通用视图
import app.urls
urlpatterns = [
path('admin/', admin.site.urls),
path('api/',include(app.urls)),
path('',TemplateView.as_view(template_name="index.html")), //路由到index.html
]
在setting.py下添加静态文件地址
STATICFILES_DIRS = [(os.path.join(BASE_DIR,'appfront/dist/static'))]
启动django 服务
python manage.py runserver
访问我们的django地址,此时django已链接到前端
参考:https://github.com/rogerlh/django_with_vue
NEXT
- django-rest-framework 创建restful api
- django wsgi的应用
文章有不足的地方欢迎在评论区指出。
欢迎收藏、点赞、提问。关注*饮水机管理员,除了管烧热水,有时还做点别的。