文章目录
- Django3后端项目创建
- 切换数据库
- 创建Django实战项目App
- 新建Vue.js前端项目
Django3后端项目创建
- 创建
Django
项目,采用Pycharm
或者命令行创建皆可。此处,以命令行方式作为演示,项目名为django_vue
。
django-admin startproject django_vue
项目结构如图所示
2. 同步数据库文件(Django
默认数据库为db.sqlite3
),执行同步过程如下:
切换路径到项目目录
cd django_vue
执行同步
python manage.py migrate
PS E:\coding\Django_learn\django_vue> python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
PS E:\coding\Django_learn\django_vue>
- 启动
Django Server
,验证默认配置是否正常。
python manage.py runserver
PS E:\coding\Django_learn\django_vue> python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
November 03, 2024 - 12:56:21
Django version 5.1.2, using settings 'django_vue.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
[03/Nov/2024 12:56:24] "GET / HTTP/1.1" 200 12068
Not Found: /favicon.ico
[03/Nov/2024 12:56:24] "GET /favicon.ico HTTP/1.1" 404 2212
切换数据库
- 将
Django
数据库更换为Mysql
登录mysql
mysql -u root -p
2. 创建数据库,数据库取名为django_vue_db
,并设置字符集为utf-8
。
mysql> CREATE DATABASE django_vue_db CHARACTER SET utf8;
Query OK, 1 row affected, 1 warning (0.15 sec)
-
安装
myslqclient
库 -
配置
settings.py
文件,配置Mysql
数据库引擎。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_vue_db',
'USER': 'root',
'PASSWORD': 'xxxxxxx',
'HOST': '127.0.0.1',
}
}
- 执行同步操作,将数据迁移到
Mysql
。
python manage.py migrate
S E:\coding\Django_learn\django_vue> python manage.py migrate
>>
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
- 验证是否切库成功,进入到
Mysql
客户端,查看django
初化表是否有生成。
mysql> use django_vue_db;
Database changed
mysql> show tables;
+----------------------------+
| Tables_in_django_vue_db |
+----------------------------+
| auth_group |
| auth_group_permissions |
| auth_permission |
| auth_user |
| auth_user_groups |
| auth_user_user_permissions |
| django_admin_log |
| django_content_type |
| django_migrations |
| django_session |
+----------------------------+
10 rows in set (0.00 sec)
- 运行
Django Server
,重新访问http://localhost:8000
如果能正常访问,过程没有报错,说明切换数据库已经成功了。
创建Django实战项目App
- 创建
Django App
,进入django_vue
项目主目录,输入如下命令:
python manage.py startapp api_test
App
创建完成后,目录结构如下所示:
并把api_test
加入到settings
文件中的installed_apps
列表里:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api_test',
]
- 在
api_test
目录下的models.py
里写一个model
:
from __future__ import unicode_literals
from django.db import models
class Book(models.Model):
book_name = models.CharField(max_length=128)
add_time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.book_name
只有两个字段,书名book_name
和添加时间add_time
。如果没有指定主键的话Django
会自动新增一个自增id
作为主键。
- 在
api_test
目录下的views
里我们新增两个接口,一个是show_books
返回所有的书籍列表(通过JsonResponse
返回能被前端识别的json
格式数据),二是add_book
接受一个get
请求,往数据库里添加一条book
数据。
from django.shortcuts import render
from django.views.decorators.http import require_http_methods
from django.core import serializers
from django.http import JsonResponse
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)
- 在
api_test
目录下,新增一个urls.py
文件,把我们新增的两个接口添加到路由里:
from django.conf.urls import url, include
from .views import *
urlpatterns = [
url(r"add_book$", add_book, ),
url(r"show_books$", show_books, ),
]
- 我们还要把
api_test
下的urls
添加到项目django_vue
下的urls
中,才能完成路由:
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from django.contrib import admin
from django.views.generic import TemplateView
import api_test.urls
urlpatterns = [
url(r"^admin/", admin.site.urls),
url(r'^api/', include(api_test.urls)),
]
- 在项目的根目录,输入命令:
python manage.py makemigrations api_test
python manage.py migrate
- 查询数据库,看到
book
表已经自动创建了:
PS E:\coding\Django_learn\django_vue> python manage.py makemigrations api_test
>>
Migrations for 'api_test':
api_test\migrations\0001_initial.py
+ Create model Book
PS E:\coding\Django_learn\django_vue> python manage.py migrate
>>
Operations to perform:
Apply all migrations: admin, api_test, auth, contenttypes, sessions
Running migrations:
Applying api_test.0001_initial... OK
Django
生成的表名将以app
名加上model
中的类名组合而成。
新建Vue.js前端项目
有关Vue
的模块(包括vue
)可以使用node
自带的npm
包管理器安装。推荐使用淘宝的 cnpm
命令行工具代替默认的 npm
。
npm install -g cnpm --registry=https://registry.npm.taobao.org
- 先用
cnpm
安装vue-cli
脚手架工具(vue-cli
是官方脚手架工具,能迅速帮你搭建起vue
项目的框架):
cnpm install -g vue-cli
PS E:\coding\Django_learn\django_vue> cnpm install -g vue-cli
>>
Downloading vue-cli to C:\Users\lenovo\AppData\Roaming\npm\node_modules\vue-cli_tmp
Copying C:\Users\lenovo\AppData\Roaming\npm\node_modules\vue-cli_tmp\.store\vue-cli@2.9.6\node_modules\vue-cli to C:\Users\lenovo\AppData\Roaming\npm\node_modules\vue-cli
Installing vue-cli's dependencies to C:\Users\lenovo\AppData\Roaming\npm\node_modules\vue-cli/node_modules
[1/20] uid@0.0.2 installed at node_modules\.store\uid@0.0.2\node_modules\uid
[2/20] commander@^2.9.0 installed at node_modules\.store\commander@2.20.3\node_modules\commander
[3/20] semver@^5.1.0 installed at node_modules\.store\semver@5.7.2\node_modules\semver
[4/20] tildify@^1.2.0 installed at node_modules\.store\tildify@1.2.0\node_modules\tildify
[5/20] user-home@^2.0.0 installed at node_modules\.store\user-home@2.0.0\node_modules\user-home
[6/20] validate-npm-package-name@^3.0.0 installed at node_modules\.store\validate-npm-package-name@3.0.0\node_modules\validate-npm-package-name
[7/20] coffee-script@1.12.7 installed at node_modules\.store\coffee-script@1.12.7\node_modules\coffee-script
[8/20] multimatch@^2.1.0 installed at node_modules\.store\multimatch@2.1.0\node_modules\multimatch
[9/20] minimatch@^3.0.0 installed at node_modules\.store\minimatch@3.1.2\node_modules\minimatch
[10/20] read-metadata@^1.0.0 installed at node_modules\.store\read-metadata@1.0.0\node_modules\read-metadata
[11/20] consolidate@^0.14.0 installed at node_modules\.store\consolidate@0.14.5\node_modules\consolidate
[12/20] chalk@^2.1.0 installed at node_modules\.store\chalk@2.4.2\node_modules\chalk
[13/20] rimraf@^2.5.0 installed at node_modules\.store\rimraf@2.7.1\node_modules\rimraf
[14/20] ora@^1.3.0 installed at node_modules\.store\ora@1.4.0\node_modules\ora
[15/20] request@^2.67.0 installed at node_modules\.store\request@2.88.2\node_modules\request
[16/20] download-git-repo@^1.0.1 installed at node_modules\.store\download-git-repo@1.1.0\node_modules\download-git-repo
[17/20] handlebars@^4.0.5 installed at node_modules\.store\handlebars@4.7.8\node_modules\handlebars
[18/20] metalsmith@^2.1.0 installed at node_modules\.store\metalsmith@2.6.3\node_modules\metalsmith
[19/20] async@^2.4.0 installed at node_modules\.store\async@2.6.4\node_modules\async
[20/20] inquirer@^6.0.0 installed at node_modules\.store\inquirer@6.5.2\node_modules\inquirer
deprecate consolidate@^0.14.0 Please upgrade to consolidate v1.0.0+ as it has been modernized with several long-awaited fixes implemented. Maintenance is supported by Forward Email at https://forwardemail.net ; follow/watch https://github.com/ladjs/consolidate for updates and release changelog
deprecate rimraf@^2.5.0 Rimraf versions prior to v4 are no longer supported
deprecate request@^2.67.0 request has been deprecated, see https://github.com/request/request/issues/3142
deprecate rimraf@2.7.1 › glob@^7.1.3 Glob versions prior to v9 are no longer supported
deprecate request@2.88.2 › har-validator@~5.1.3 this library is no longer supported
deprecate rimraf@2.7.1 › glob@7.2.3 › inflight@^1.0.4 This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
deprecate request@2.88.2 › uuid@^3.3.2 Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
Run 1 script(s) in 1s.
All packages installed (231 packages installed from npm registry, used 12s(network 12s), speed 514.2KB/s, json 222(1.25MB), tarball 4.73MB, manifests cache hit 0, etag hit 0 / miss 0)
[vue-cli@2.9.6] link C:\Users\lenovo\AppData\Roaming\npm\vue@ -> C:\Users\lenovo\AppData\Roaming\npm\node_modules\vue-cli\bin\vue
[vue-cli@2.9.6] link C:\Users\lenovo\AppData\Roaming\npm\vue-init@ -> C:\Users\lenovo\AppData\Roaming\npm\node_modules\vue-cli\bin\vue-init
[vue-cli@2.9.6] link C:\Users\lenovo\AppData\Roaming\npm\vue-list@ -> C:\Users\lenovo\AppData\Roaming\npm\node_modules\vue-cli\bin\vue-list
- 安装好后,在
django_vue
项目根目录下,新建一个前端工程目录:
vue-init webpack frontend
PS E:\coding\Django_learn\django_vue> vue-init webpack frontend
>>
? Project name frontend
? Project description A Vue.js project
? Author aliyun5171063201 <19377056@buaa.edu.cn>
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? Yes
? Pick an ESLint preset Standard
? Set up unit tests Yes
? Pick a test runner jest
? Setup e2e tests with Nightwatch? Yes
? Should we run `npm install` for you after the project has been created? (recommended) npm
vue-cli · Generated "frontend".
# Installing project dependencies ...
# ========================
npm warn deprecated inflight@1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
npm warn deprecated stable@0.1.8: Modern JS already guarantees Array#sort() is a stable sort, so this library is deprecated. See the compatibility table on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#browser_compatibility
npm warn deprecated rimraf@2.7.1: Rimraf versions prior to v4 are no longer supported
npm warn deprecated har-validator@5.1.5: this library is no longer supported
npm warn deprecated glob@7.2.3: Glob versions prior to v9 are no longer supported
npm warn deprecated source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated
npm warn deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm warn deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm warn deprecated source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated
npm warn deprecated flatten@1.0.3: flatten is deprecated in favor of utility frameworks such as lodash.
npm warn deprecated acorn-dynamic-import@2.0.2: This is probably built in to whatever tool you're using. If you still
need it... idk
npm warn deprecated consolidate@0.14.5: Please upgrade to consolidate v1.0.0+ as it has been modernized with several long-awaited fixes implemented. Maintenance is supported by Forward Email at https://forwardemail.net ; follow/watch https://github.com/ladjs/consolidate for updates and release changelog
npm warn deprecated json3@3.3.2: Please use the native JSON object instead of JSON 3
npm warn deprecated uuid@3.4.0: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
npm warn deprecated copy-concurrently@1.0.5: This package is no longer supported.
npm warn deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm warn deprecated request-promise-native@1.0.9: request-promise-native has been deprecated because it extends the now deprecated request package, see https://github.com/request/request/issues/3142
npm warn deprecated socks@1.1.10: If using 2.x branch, please upgrade to at least 2.1.6 to avoid a serious bug with socket data flow and an import issue introduced in 2.1.0
npm warn deprecated q@1.4.1: You or someone you depend on is using Q, the JavaScript Promise library that gave JavaScript developers strong feelings about promises. They can almost certainly migrate to the native JavaScript promise now. Thank you literally everyone for joining me in this bet against the odds. Be excellent to each other.
npm warn deprecated
npm warn deprecated (For a CapTP with native promises, see @endo/eventual-send and @endo/captp)
npm warn deprecated abab@2.0.6: Use your platform's native atob() and btoa() methods instead
npm warn deprecated domexception@1.0.1: Use your platform's native DOMException instead
npm warn deprecated w3c-hr-time@1.0.2: Use your platform's native performance.now() and performance.timeOrigin.
npm warn deprecated left-pad@1.3.0: use String.prototype.padStart()
npm warn deprecated fs-write-stream-atomic@1.0.10: This package is no longer supported.
npm warn deprecated move-concurrently@1.0.1: This package is no longer supported.
npm warn deprecated circular-json@0.3.3: CircularJSON is in maintenance only, flatted is its successor.
npm warn deprecated sane@2.5.2: some dependency vulnerabilities fixed, support for node < 10 dropped, and newer ECMAScript syntax/features added
npm warn deprecated eslint-loader@1.9.0: This loader has been deprecated. Please use eslint-webpack-plugin
npm warn deprecated chromedriver@2.46.0: Chromedriver download url has changed. Use version 114.0.2 or newer.
npm warn deprecated browserslist@2.11.3: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
npm warn deprecated html-webpack-plugin@2.30.1: out of support
npm warn deprecated browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
npm warn deprecated rimraf@2.6.3: Rimraf versions prior to v4 are no longer supported
npm warn deprecated glob@7.0.5: Glob versions prior to v9 are no longer supported
npm warn deprecated extract-text-webpack-plugin@3.0.2: Deprecated. Please use https://github.com/webpack-contrib/mini-css-extract-plugin
npm warn deprecated browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
npm warn deprecated uglify-es@3.3.10: support for ECMAScript is superseded by `uglify-js` as of v3.13.0 ([WARNING] Use 3.3.9 instead of 3.3.10, reason: see https://github.com/mishoo/UglifyJS2/issues/2896)
npm warn deprecated bfj-node4@5.3.1: Switch to the `bfj` package for fixes and new features!
npm warn deprecated babel-eslint@8.2.6: babel-eslint is now @babel/eslint-parser. This package will no longer receive
updates.
npm warn deprecated browserslist@1.7.7: Browserslist 2 could fail on reading Browserslist >3.0 config used in other tools.
npm warn deprecated mkdirp@0.5.1: Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)
npm warn deprecated svgo@0.7.2: This SVGO version is no longer supported. Upgrade to v2.x.x.
npm warn deprecated svgo@1.3.2: This SVGO version is no longer supported. Upgrade to v2.x.x.
npm warn deprecated vue@2.7.16: Vue 2 has reached EOL and is no longer actively maintained. See https://v2.vuejs.org/eol/ for more details.
npm warn deprecated eslint@4.19.1: This version is no longer supported. Please see https://eslint.org/version-support
for other options.
npm warn deprecated core-js@2.6.12: core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Some versions have web compatibility issues. Please, upgrade your dependencies to the actual version of core-js.
added 1908 packages in 2m
122 packages are looking for funding
run `npm fund` for details
Running eslint --fix to comply with chosen preset rules...
# ========================
> frontend@1.0.0 lint
> eslint --ext .js,.vue src test/unit test/e2e/specs --fix
在创建项目的过程中会弹出一些与项目相关的选项需要回答,按照真实情况进行输入即可。
- 安装
vue
依赖模块
cd frontend
cnpm install
cnpm install vue-resource
cnpm install element-ui
PS E:\coding\Django_learn\django_vue> cnpm install vue-resource
√ Linked 31 latest versions fallback to E:\coding\Django_learn\django_vue\node_modules\.store\node_modules
tly_updates.txt)
Today:
→ vue-resource@1.5.3 › got@11.8.6 › @types/cacheable-request@6.0.3 › @types/node@*(22.8.7) (12:02:53)
√ Installed 1 packages on E:\coding\Django_learn\django_vue
√ All packages installed (32 packages installed from npm registry, used 2s(network 2s), speed 387.11KB/s, json 25(139.05KB), tarball 652.98KB, manifests cache hit 6, etag hit 6 / miss 0)
dependencies:
+ vue-resource ^1.5.3
PS E:\coding\Django_learn\django_vue> cnpm install element-ui
>>
√ Linked 10 latest versions fallback to E:\coding\Django_learn\django_vue\node_modules\.store\node_modules
√ Linked 2 public hoist packages to E:\coding\Django_learn\django_vue\node_modules
peerDependencies WARNING element-ui@latest requires a peer of vue@^2.5.17 but none was installed, packageDir: E:\coding\Django_learn\django_vue\node_modules\.store\element-ui@2.15.14\node_modules\element-ui
deprecate element-ui@2.15.14 › async-validator@1.8.5 › babel-runtime@6.26.0 › core-js@^2.4.0 core-js@<3.23.3 is no longer maintained and not recommended for usage due to the number of issues. Because of the V8 engine whims, feature detection in old core-js versions could cause a slowdown up to 100x even if nothing is polyfilled. Some versions have web
compatibility issues. Please, upgrade your dependencies to the actual version of core-js.
√ Run 1 script(s) in 176ms.
√ Installed 1 packages on E:\coding\Django_learn\django_vue
√ All packages installed (10 packages installed from npm registry, used 4s(network 4s), speed 603.25KB/s, json 10(174.66KB), tarball 2.37MB, manifests cache hit 0, etag hit 0 / miss 0)
dependencies:
+ element-ui ^2.15.14
- 现在我们可以看到整个文件目录结构是这样的:
6. 在frontend
目录src
下包含入口文件main.js
,入口组件App.vue
等。后缀为vue
的文件是Vue.js
框架定义的单文件组件,其中标签中的内容可以理解为是类html
的页面结构内容。
- 在
src/component
文件夹下新建一个名为Home.vue
的组件,通过调用之前在Django
上写好的api
,实现添加书籍和展示书籍信息的功能。在样式组件上我们使用了饿了么团队推出的element-ui
,这是一套专门匹配Vue.js
框架的功能样式组件。