基於Web框架Django、前端框架Vue.js 、 ElementUi ,實現前后端分離項目環境搭建詳細流程


Django+vue+ElementUi

本文主要分為五個部分,逐一進行講解前后端分離項目環境搭建流程,主要有:環境搭建、Django、vue、整合、總結;

一、 環境搭建

開發工具:VsCode
下載鏈接:https://code.visualstudio.com/Download
安裝教程:https://www.runoob.com/w3cnote/vscode-tutorial.html
開發語言:Python
下載鏈接:https://www.python.org/downloads/windows/
安裝教程: https://www.runoob.com/python3/python3-install.html
框架:Django
下載鏈接:https://www.djangoproject.com/download/
安裝教程:https://www.runoob.com/django/django-install.html
Node.js
下載鏈接:https://nodejs.org/en/download/
安裝教程:https://www.runoob.com/nodejs/nodejs-install-setup.html
數據庫:mysql
下載鏈接:https://dev.mysql.com/downloads/mysql/
安裝教程:https://www.runoob.com/mysql/mysql-tutorial.html

二、 Django

2.1 創建項目

命令行:django-admin startproject 項目名
驗證:python manage.py runserver

2.2 數據庫配置

安裝完MySQL 建好數據庫
cmd窗口登錄MySQL:mysql -uroot -p
安裝python的pymysql包:pip install pymysql
創建數據庫:create DATABASE 數據庫名稱 DEFAULT CHARSET utf8;
配置數據庫:在setting.py 查找 DATABASES
修改數據庫連接信息:

DATABASES = {
'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
# 自定義數據庫
'ENGINE': 'django.db.backends.mysql', # 數據庫引擎
'NAME': 'Django_ElementUI', # 數據庫名稱
'HOST': '127.0.0.1', # 數據庫地址,本機 ip 地址 127.0.0.1
'PORT': 3306, # 端口
'USER': 'root', # 數據庫用戶名
'PASSWORD': '', # 數據庫密碼
}
}

引入模塊:在 init.py文件里增加:

import pymysql
pymysql.install_as_MySQLdb()

2.3 創建模型並且設計數據庫表 Django app :myApp
命令行:python manage.py startapp myApp
設計數據庫:在myApp 文件夾內打開models.py文件
插入要創建的表內容,注意每行縮進

點擊查看代碼
from django.db import models

# Create your models here.
class Student(models.Model):
    student_name = models.CharField(max_length=64)
    student_sex = models.CharField(max_length=3)
    create_time = models.DateTimeField(auto_now_add=True)
    def __unicode__(self):
        return self.Student_name
        return self.id

在setting.py文件,在INSTALLED_APPS中 添加'myApp'

點擊查看代碼

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myApp',#添加此項
]

在項目目錄下 啟動cmd 依次執行下面兩句命令,生成數據庫遷移文件:
python manage.py migrate
python manage.py makemigrations myApp

執行遷移文件 完成數據庫表的創建
python manage.py migrate myApp

表名:由myapp_student組成

2.4 創建新增和查詢的接口
views.py
創建兩個視圖函數
作為接口 給前端調用

點擊查看代碼
# Create your views here.
from __future__ import unicode_literals

import json

from django.core import serializers
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.http import require_http_methods

from myApp.models import Student


#創建view 
#add_student 接受一個get請求 網數據里添加一條student 數據
@require_http_methods(["GET"])
def add_student(request):
    response = {}
    try:
        student = Student(student_name=request.GET.get('student_name'))
        student.save()
        response['msg']="success"
        response['error_num']=0
    except Exception as e:
            response['msg'] = str(e)
            response['error_num'] = 1
    return JsonResponse(response)

# show_students返回所有的學生列表(通過JsonResponse返回能被前端識別的json格式數據)
@require_http_methods(["GET"])
def show_students(request):
    response = {}
    try:
        students = Student.objects.filter()
        response['list'] = json.loads(serializers.serialize("json", students))
        response['msg'] = 'success'
        response['error_num'] = 0
    except Exception as e:
        response['msg'] = str(e)
        response['error_num'] = 1
 
    return JsonResponse(response)

配置路由
配置分支路由,myApp下新增文件:urls.py
創建分支路由,把新增的兩個視圖函數放進來

from django.conf.urls import url

from myApp import views

urlpatterns = [
url('add_student/',views.add_student),
url('show_students/',views.show_students),

]

將分支路由加到項目文件夾下的主路由中urls.py;

from django.conf.urls import include, url
from django.contrib import admin
from django.views.generic import TemplateView # 新增
from myApp import urls

urlpatterns = [
url(r'^admin/',admin.site.urls),
url(r'^api/',include(urls)),
#新增
url(r'^$',TemplateView.as_view( template_name="index.html" ) )
]

三、Vue

3.1、安裝腳手架vue-cli

npm install -g vue-cli

3.2、新建前端工程項目

vue-init webpack 項目名稱

3.3、安裝依賴包

npm install 包名稱

3.4、安裝ElementUI

npm i element-ui -S

3.5、創建vue界面

在src/component下,新建組件Student.vue
調用之前在Django項目里的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="addStudent()" style="float:left; margin: 2px;">新增</el-button>
    </el-row>
    <el-row>
        <el-table :data="studentList" style="width: 100%" border>
          <el-table-column prop="id" label="編號" min-width="100">
            <template slot-scope="scope"> {{ scope.row.pk }} </template>
          </el-table-column>
          <el-table-column prop="student_name" label="姓名" min-width="100">
            <template slot-scope="scope"> {{ scope.row.fields.student_name }} </template>
          </el-table-column>
          <el-table-column prop="student_sex" label="性別" min-width="100">
            <template slot-scope="scope"> {{ scope.row.fields.student_sex }} </template>
          </el-table-column>
          <el-table-column prop="add_time" label="添加時間" min-width="100">
            <template slot-scope="scope"> {{ scope.row.fields.create_time }} </template>
          </el-table-column>
        </el-table>
    </el-row>
  </div>
</template>

<script>
export default {
  name: 'Student',
  data () {
    return {
      input: '',
      studentList: []
    }
  },
  mounted: function () {
    this.showStudents()
  },
  methods: {
    addStudent () {
      this.$http.get('http://127.0.0.1:8000/api/add_student?student_name=' + this.input)
        .then((response) => {
          var res = JSON.parse(response.bodyText)
          if (res.error_num === 0) {
            this.showStudents()
          } else {
            this.$message.error('新增學生失敗,請重試')
            console.log(res['msg'])
          }
        })
    },
    showStudents () {
      this.$http.get('http://127.0.0.1:8000/api/show_students')
        .then((response) => {
          var res = JSON.parse(response.bodyText)
          console.log(res)
          if (res.error_num === 0) {
            this.studentList = res['list']
            console.log(this.studentList)
          } 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>

3.6、配置路由
appfront/router文件夾下的index.js中增加頁面路由;

點擊查看代碼
import HelloWorld from '@/components/HelloWorld'
import Student from '@/components/Student'
import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)
export default new Router({
    routes: [{
                path: '/HelloWorld',
                name: 'HelloWorld',
                component: HelloWorld
            },
            {
                path: '/student',
                name: 'Student',
                component: Student
            }
        ]
        // eslint-disable-next-line eol-last
})

appfront文件夾下的main.js中引入ElementUI並注冊:

點擊查看代碼
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import 'default-passive-events'
import ElementUI from 'element-ui'
import Vue from 'vue'
// 引入vue-resource
import VueResource from 'vue-resource'
// 注冊ElementUI組件
import '../node_modules/element-ui/lib/theme-chalk/index.css'
import App from './App'
import router from './router'
Vue.config.productionTip = false

// 注冊ElementUI組件
Vue.use(ElementUI)
    // 注冊VueResource
Vue.use(VueResource)

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    components: { App },
    template: '<App/>'
        // eslint-disable-next-line eol-last
})

3.7、打包並啟動前端項目

npm run build
npm run dev

然后去瀏覽器訪問頁面地址:http://localhost:8080/#/student

四、 整合

4.1、前端vue項目調用后端引入vue-resource

在appfront文件下運行命令:
npm install --save vue-resource

在main.js中引入vue-resource

import VueResource from 'vue-resource'
Vue.use(VueResource)

4.2、在Django層注入header

用Django的第三方包django-cors-headers來解決跨域問題
在DjangoElementUI根目錄下輸入命令:
pip install django-cors-headers

在settings.py中增加相關中間件代碼
在MIDDLEWARE增加:

'corsheaders.middleware.CorsMiddleware'
CORS_ORIGIN_ALLOW_ALL = True

4.3、增加Django路由

把Django的TemplateView指向我們剛才生成的前端dist文件
在DjangoElementUI目錄下的urls.py中增加代碼:
from django.views.generic import TemplateView

修改靜態資源文件路徑以及指向前端appfront 相關文件
在DjangoElementUI目錄下的setting.py中增加代碼:
'DIRS': [os.path.join(BASE_DIR, 'appfront/dist')],

增加此項 for vue.js

STATICFILES_DIRS = [
os.path.join(BASE_DIR, "appfront/dist/static")
]

4.4、重新構建前端項目

npm run build
python manage.py runserver

五、 總結

1、python 運行過程中,需要什么包,安裝什么包;
python 包庫:https://pypi.org/
2、數據庫創建的過程中,一定要注意大小寫的問題,數據庫字段和Django的Models頁面,View頁面和Vue中的組件頁面都有關聯.很容易一個大小寫不注意,導致整個接口無法使用.
3、連接MySQL需要按照對應的包,同時需要在根目錄的_ini_.py中引入pymysql
4、在整個環境的搭建過程中VUE環境的搭建需要耗費較長的npm安裝時間,需要耐心等待.
5、前后台連接需要在前端引入vue-resource,Django需要引入django-cors-headers


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM