環(huán)境:windows 7霎褐、django1.11合敦、python3.6.3
1. 使用virtualenv創(chuàng)建python虛擬環(huán)境并設(shè)置pycharm
E:\pyvenv>virtualenv utester_env
E:\pyvenv>cd utester_env
E:\pyvenv>Scripts\activate.bat
(utester_env) E:\pyvenv>pip install django
(utester_env) E:\pyvenv\utester_env>pip install django
Requirement already satisfied: django in e:\pyvenv\utester_env\lib\site-packages
Requirement already satisfied: pytz in e:\pyvenv\utester_env\lib\site-packages (
from django)
注意:虛擬環(huán)境的目錄不能帶有中文维费,否則環(huán)境變量識(shí)別不了
2.創(chuàng)建Django項(xiàng)目
(utester_env) E:\projects>django-admin startproject utester
(utester_env) E:\projects>cd utester
#創(chuàng)建表
(utester_env) E:\projects\utester>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 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 sessions.0001_initial... OK
#創(chuàng)建管理員用戶
(utester_env) E:\projects\utester>python manage.py createsuperuser
Username (leave blank to use 'zengzhihua'):
Email address: 1036181341@qq.com
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Password:
Password (again):
Superuser created successfully.
(utester_env) E:\projects\utester>python manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
October 09, 2017 - 14:05:32
Django version 1.11.6, using settings 'utester.settings'
Starting development server at http://127.0.0.1:8000/
訪問http://127.0.0.1:8000/admin/潮梯,輸入剛剛創(chuàng)建的用戶名和密碼蹬昌,如果一切順利,就可以看到django的admin管理后臺(tái)了昧捷。
3.創(chuàng)建vue項(xiàng)目
關(guān)于django、vue前后端分離罐寨,在github上有個(gè)模板hello-vue-django靡挥,源倉庫地址hello-vue-django。但我看不慣python和js文件鸯绿,想把vue項(xiàng)目代碼單獨(dú)放一個(gè)目錄frontend跋破。
在utester項(xiàng)目目錄利用vue-cli新建vue的項(xiàng)目代碼
(utester_env) E:\projects\utester>vue init webpack frontend
A newer version of vue-cli is available.
latest: 2.9.1
installed: 2.8.2
? Project name utester
? Project description A Vue.js project
? Author zengzhihua
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? No
? Setup unit tests with Karma + Mocha? No
? Setup e2e tests with Nightwatch? No
vue-cli · Generated "frontend".
To get started:
cd frontend
npm install
npm run dev
Documentation can be found at https://vuejs-templates.github.io/webpack
最終項(xiàng)目目錄結(jié)構(gòu)如下:
(utester_env) E:\projects\utester>tree /f
卷 NewDisk 的文件夾 PATH 列表
卷序列號(hào)為 6A28-026B
E:.
│ db.sqlite3
│ manage.py
│
├─frontend
│ │ .babelrc
│ │ .editorconfig
│ │ .gitignore
│ │ .postcssrc.js
│ │ index.html
│ │ package.json
│ │ README.md
│ │
│ ├─build
│ │ build.js
│ │ check-versions.js
│ │ dev-client.js
│ │ dev-server.js
│ │ utils.js
│ │ vue-loader.conf.js
│ │ webpack.base.conf.js
│ │ webpack.dev.conf.js
│ │ webpack.prod.conf.js
│ │
│ ├─config
│ │ dev.env.js
│ │ index.js
│ │ prod.env.js
│ │
│ ├─src
│ │ │ App.vue
│ │ │ main.js
│ │ │
│ │ ├─assets
│ │ │ logo.png
│ │ │
│ │ ├─components
│ │ │ HelloWorld.vue
│ │ │
│ │ └─router
│ │ index.js
│ │
│ └─static
│ .gitkeep
│
├─imonitor
│ │ admin.py
│ │ apps.py
│ │ models.py
│ │ tests.py
│ │ views.py
│ │ __init__.py
│ │
│ └─migrations
│ __init__.py
│
└─utester
│ settings.py
│ urls.py
│ wsgi.py
│ __init__.py
│
└─__pycache__
settings.cpython-36.pyc
urls.cpython-36.pyc
wsgi.cpython-36.pyc
__init__.cpython-36.pyc
4.配置django-webpack-loader
參考文章:用django-webpack-loader實(shí)現(xiàn)Django和Webpack的綁定 和django-webpack配置
-
安裝django-webpack-loader
安裝遇到個(gè)報(bào)錯(cuò)簸淀,大致意思是ssl驗(yàn)證失敗了,如下:
(utester_env) E:\pyvenv\utester_env>Scripts\pip.exe install django-webpack-load
er
Collecting django-webpack-loader
Could not fetch URL https://pypi.python.org/simple/django-webpack-loader/: The
re was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED
] certificate verify failed (_ssl.c:749) - skipping
Could not find a version that satisfies the requirement django-webpack-loader
(from versions: )
這個(gè)錯(cuò)誤毒返,時(shí)有時(shí)無的租幕,也不清楚是怎么回事,import ssl是沒有問題的拧簸。所以只能跳過ssl驗(yàn)證劲绪,命令如下:
pip install --index-url=http://pypi.python.org/simple/ --trusted-host pypi.python.org django-webpack-loader
然后設(shè)置Django( settings.py ),把 webpack_loader 加到INSTALLED_APPS中狡恬,指定templates和static目錄珠叔,新增WEBPACK_LOADER:
INSTALLED_APPS = [
...
'webpack_loader',
]
STATIC_URL = '/static/'
#靜態(tài)文件主目錄
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'frontend/dist/static'),
)
#針對(duì)Webpack的設(shè)置
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'dist/'
}
}
很奇怪1.11版本為什么沒有STATICFILES_DIRS 變量了蝎宇。我自己加上去的弟劲,不知道會(huì)不會(huì)有問題
-
配置templates相關(guān)
更改settings里templates,DIRS里增加os.path.join(BASE_DIR, 'templates'),這樣django在尋找模板文件的時(shí)候姥芥,就會(huì)從這個(gè)列表目錄按順序查找兔乞,直到匹配為止
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(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',
],
},
},
]
新建templates目錄以及index.html文件,文件內(nèi)容如下:
<!DOCTYPE html>
{% load render_bundle from webpack_loader %}
<html lang="en">
<head>
<meta charset="utf-8">
<title>hello-vue</title>
</head>
<body>
<div id="app"></div>
{% render_bundle 'app' %}
</body>
</html>
- 配置webpack 的dev環(huán)境
- 安裝webpack-bundle-tracker
安裝前記得npm install一下凉唐,將其他vue的依賴都安裝完庸追,安裝完后node_modules目錄非常大,pycharm一直pycharm scanning files to index台囱,導(dǎo)致電腦非车荩卡,一不小心就內(nèi)存崩潰了簿训≡廴ⅲ可以將該目錄標(biāo)記為不掃描,右鍵node_modules强品,mark directory as Exclude膘侮,這樣
(utester_env) E:\projects\utester>npm install --save-dev webpack-bundle-tracker
npm WARN saveError ENOENT: no such file or directory, open 'E:\projects\utester\
package.json'
E:\projects\utester
`-- webpack-bundle-tracker@0.2.0
+-- deep-extend@0.4.2
+-- mkdirp@0.5.1
| `-- minimist@0.0.8
`-- strip-ansi@2.0.1
`-- ansi-regex@1.1.1
- 更改webpack.dev.conf.js文件
引入webpack-bundle-tracker
var BundleTracker = require('webpack-bundle-tracker');
#plugins數(shù)組增加如下,filename于settings里的WEBPACK_LOADER一致
new BundleTracker({filename: '../webpack-stats.json'}),
3.更改webpack的config/index.js
#增加兩個(gè)變量
const dev_server_addr = 'localhost';
const dev_server_port = process.env.PORT || 8080
#修改以下兩個(gè)變量
port: dev_server_port,
assetsPublicPath: 'http://' + dev_server_addr + ':' + dev_server_port + '/static/dist' + '/',
5.啟動(dòng)dev環(huán)境
- 啟動(dòng)django項(xiàng)目
(utester_env) E:\projects\utester>python manage.py runserver
Performing system checks...
System check identified no issues (0 silenced).
October 09, 2017 - 21:13:05
Django version 1.11.6, using settings 'utester.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
- 啟動(dòng)vue項(xiàng)目
(utester_env) E:\projects\utester\frontend>npm run dev
> frontend@1.0.0 dev E:\projects\utester\frontend
> node build/dev-server.js
> Starting dev server...
DONE Compiled successfully in 3188ms 20:54:11
> Listening at http://localhost:8080
-
訪問http://127.0.0.1:8000/
如果一切順利的榛,應(yīng)該可以看到熟悉的vue頁面了
到這里琼了,留下一個(gè)問題,就是更改frontend里的內(nèi)容夫晌,不會(huì)同步刷新頁面雕薪,只能手動(dòng)刷新才能看到效果,熱加載功能失效了晓淀∷看瀏覽器的network里,有一個(gè)404的資源http://127.0.0.1:8000/__webpack_hmr要糊,看樣子是端口錯(cuò)了纲熏,應(yīng)該是訪問vue開啟的8080端口妆丘。還沒找到解決方法
本文所有代碼:django-vue-helloworld
參考文獻(xiàn):
github:https://github.com/zaxlct/hello-vue-django