我的独立博客链接:https://maguodong.com
搭建python Django基本环境
创建虚拟环境
python3 -m venv v_info
|-- infomanage
| |-- v_info
激活虚拟环境
source v_info/bin/activate
安装django
pip install Django
django会被安装到v_info/lib/site-package/下
创建django项目
django-admin.py startproject infomanage .(不能忘记点)
|-- infomanage | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py |-- v_info `-- manage.py
创建应用
python manage.py startapp infomanages
|-- infomanage | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py |-- infomanages |-- v_info `-- manage.py
在settings中添加应用并在根目录的urls中添加应用路径
settings.py:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.content*', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 我的应用 'infomanages', ]
urls.py:
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('home/', include('infomanages.urls')) ]
在应用目录下创建urls.py文件,并导入path,views,设置路径
from django.urls import path from . import views app_name = 'linkslibs' urlpatterns = [ path('index', views.index, name='index') ]
创建视图模版
在infomanages目录下创建一个templates文件夹,里面再创建一个infomanages文件夹,文件夹内创建一个index.html文件,里面输入Hello, Django
在应用目录下的views.py中创建视图
from django.shortcuts import render from django.http import HttpResponseRedirect, Http404 # Create your views here. def index(request): return render(request, 'infomanages/index.html') ---- 跳转到模版页面
这个时候启动项目:python manage.py runserver,在地址栏中输入localhost:8000/home/index就能看到页面了
安装pymysql,连接数据库
安装pymysql
pip3 install pymysql并在根目录__init__.py中导入pymysql
import pymysql pymysql.install_as_MySQLdb()
在setting.py中设置数据库信息(需提前创建好数据库)
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'info', 'USER': 'root', 'PASSWORD': 'Eric54920', 'HOST': 'localhost', 'PORT': '3306' } }
创建数据模型
在infomanages/models.py中编写模型类
from django.db import models # Create your models here. class Info(models.Model): info_id = models.AutoField(primary_key=True) name = models.CharField(max_length=20) desc = models.CharField(max_length=200)
注册模型类
在admin.py中注册模型类
from django.contrib import admin from infomanages.models import Info # Register your models here. admin.site.register(Info)
创建迁移
python manage.py makemigrations
命令行显示:
Migrations for 'infomanages': infomanages/migrations/0001_initial.py - Create model Info
这个时候infomanages/migrations下目录结构会增加一个0001_initial.py文件
|-- migrations | |-- __pycache__ | |-- 0001_initial.py | `-- __init__.py
执行迁移
python manage.py migrate
命令行显示:
System check identified some issues: WARNINGS: ?: (mysql.W002) MySQL Strict Mode is not set for database connection 'default' HINT: MySQL's Strict Mode fixes many data integrity problems in MySQL, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/2.2/ref/databases/#mysql-sql-mode Operations to perform: Apply all migrations: admin, auth, content*, infomanages, sessions Running migrations: Applying content*.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 content*.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_content*_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 infomanages.0001_initial... OK Applying sessions.0001_initial... OK (v_info) localhost:infomanage maguodong$
再次运行项目
python manage.py runserver,这个时候访问localhost:8000/admin就会显示django管理员页面
接下来需要创建一个超级管理员账号
使用命令行创建超级管理员账号
python manage.py createsupersuer
命令行显示:
Username (leave blank to use 'maguodong'): admin Email address: ---- 可填可不填 Password: ---- 密码会隐藏 Password (again): Superuser created successfully.
登录管理员账号
再次运行项目访问localhost:8000/admin登录账号密码,将会看到多了一个数据表
现在使用管理页面插入一条数据
name:Hello, ORM
desc:this is a python ORM project
点击SAVE之后将会看到列表中多了一条数据
在数据库的infomanages_info表中也能看到这条数据
接下来在index.html中展示数据。
数据查询和展示
修改infomanages/views.py
from django.shortcuts import render from django.http import HttpResponseRedirect, Http404 from .models import Info # Create your views here. def index(request): infos = Info.objects.get(info_id=1) context = {'infos': infos} return render(request, 'infomanages/index.html', context)
然后修改templates/infamanages/index.html
{% block header %} <h3>infos:</h3> {% endblock header %} {% block content %} <h4>{{ infos.name }}</h4> <p>{{ infos.desc }}</p> {% endblock content %}
再次访问localhost/home/index将看到刚才插入的一条数据
再从管理员页面插入一条数据进行数据遍历展示
再次修改views.py和index.html
views.py
def index(request): infos = Info.objects.all() context = {'infos': infos} return render(request, 'infomanages/index.html', context) index.html {% block header %} <h3>infos:</h3> {% endblock header %} {% block content %} <ul> {% for info in infos %} <li><span>{{ info.name }}</span>——{{ info.desc }}</li> {% empty %} <li>no have info</li> {% endfor %} </ul> {% endblock content %}
运行项目后数据展示如下:
安装前台vue框架
初始化Vue应用
使用命令行工具进入infomanage,执行命令
vue init webpack frontend ? Project name frontend ? Project description A Vue.js project ? Author Eric54920 <mgd54920@gmail.com> ? Vue build standalone ? Install vue-router? Yes ? Use ESLint to lint your code? No ? Set up unit tests No ? Setup e2e tests with Nightwatch? No ? Should we run `npm install` for you after the project has been created? (recom mended) npm vue-cli · Generated "frontend". # Installing project dependencies ... # Project initialization finished! # ======================== To get started: cd frontend npm run dev Documentation can be found at https://vuejs-templates.github.io/webpack
设置模版目录
修改settings.py中的模版目录
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['frontend/dist'], # 修改目录 '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', ], }, }, ]
在settings.py文件后加上以下代码
STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'frontend/dist/static') ]
然后修改views.py文件
def index(request): infos = Info.objects.all() context = {'infos': infos} return render(request, 'index.html', context)
打包运行项目
进入frontend
cd frontend npm run build > frontend@1.0.0 build /Users/maguodong/Documents/python/infomanage/frontend > node build/build.js Hash: 44a1d344d9003e2897f6 Version: webpack 3.12.0 Time: 5044ms Asset Size Chunks Chunk Names static/js/vendor.eefaac73d06c156e050b.js 120 kB 0 [emitted] vendor static/js/app.b22ce679862c47a75225.js 11.6 kB 1 [emitted] app static/js/manifest.2ae2e69a05c33dfc65f8.js 857 bytes 2 [emitted] manifest static/css/app.30790115300ab27614ce176899523b62.css 432 bytes 1 [emitted] app static/css/app.30790115300ab27614ce176899523b62.css.map 828 bytes [emitted] static/js/vendor.eefaac73d06c156e050b.js.map 602 kB 0 [emitted] vendor static/js/app.b22ce679862c47a75225.js.map 22.2 kB 1 [emitted] app static/js/manifest.2ae2e69a05c33dfc65f8.js.map 4.97 kB 2 [emitted] manifest index.html 510 bytes [emitted] Build complete. Tip: built files are meant to be served over an HTTP server. Opening index.html over file:// won't work.
然后再次访问localhost:8000/home/index就会看到Vue的初始化页面
修改infomanages/views.py
删除之前添加的index方法,新增show_info方法
from django.shortcuts import render from django.http import JsonResponse from django.views.decorators.http import require_http_methods from django.core import serializers from .models import Info import json @require_http_methods(['GET']) def show_info(request): response = {} try: info = Info.objects.filter() response['list'] = json.loads(serializers.serialize('json', info)) response['msg'] = 'success' response['error_num'] = 0 except Exception(e): response['msg'] = str(e) response['error_num'] = 1 return JsonResponse(response)
在infomanages/urls.py修改api
urlpatterns = [ path('show_info', views.show_info, ), ]
修改infomanage/urls.py
from django.contrib import admin from django.urls import path, include import infomanages.urls urlpatterns = [ path('admin/', admin.site.urls), # path('home/', include('infomanages.urls')) path('api/', include('infomanages.urls')) ]
然后先用postman来测试一下接口是否正常
没有postman的小伙伴可以先去下载一个postman,测试接口很常用
也可以启动项目在浏览器中测试
localhost:8000/api/show_info显示结果和postman中的一样。
修改HelloWorld.vue页面
修改HelloWorld.vue为Heme.vue,删除之前的所有内容,修改为以下内容:
<template> <div> <ul v-for="item in infoList"> <li>{{ item['fields']['name'] }}, {{ item['fields']['desc'] }}</li> </ul> </div> </template> <script type='text/ecmascript-6'> export default { name: 'home', data () { return { infoList: [] } }, mounted: function() { this.showInfos(); }, methods: { showInfos () { this.$http.get('http://127.0.0.1:8000/api/show_info').then((response) => { let res = JSON.parse(response.bodyText); console.log(res); if (res.error_num == 0) { this.infoList = res['list']; } else { this.$massage.error = '查询信息失败'; console.log(res['msg']); } }) } } } </script> <style type='text/css' scoped> li { text-align: left; } </style>
配置路由
在src/router/index.js中导入Home.vue,并为其配置路由
import Home from '@/components/Home' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Home', component: Home } ] })
现在如果运行项目会出现跨域请求错误
npm run dev
安装django-cors-headers解决跨域问题
pip3 install django-cors-headers Collecting django-cors-headers Downloading https://files.pythonhosted.org/packages/07/10/14e9a34fed4f4c692a2863ae1e3591de56acb70295100aa9db89fc32bd92/django_cors_headers-3.0.2-py2.py3-none-any.whl Requirement already satisfied: Django>=1.11 in ./v_info/lib/python3.7/site-packages (from django-cors-headers) (2.2.2) Requirement already satisfied: pytz in ./v_info/lib/python3.7/site-packages (from Django>=1.11->django-cors-headers) (2019.1) Requirement already satisfied: sqlparse in ./v_info/lib/python3.7/site-packages (from Django>=1.11->django-cors-headers) (0.3.0) Installing collected packages: django-cors-headers Successfully installed django-cors-headers-3.0.2 You are using pip version 19.0.3, however version 19.1.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. (v_info) maguodongdeMacBook-Pro:infomanage maguodong$
修改settings.py
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', # 注意添加顺序 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True
整合Django与Vue
目前我们已经分别完成了Django后端和Vue.js前端工程的创建和编写,但实际上它们是运行在各自的服务器上,和我们的要求是不一致的。因此我们须要把Django的TemplateView指向我们刚才生成的前端dist文件即可。
在infomanages/urls.py中添加一条路径
path('home/',TemplateView.as_view(template_name="index.html")),
重新打包Vue项目npm run build,再次运行django项目python manage.py runserver,地址栏中输入localhost:8000/home,页面显示如下:
关于命令行报错
1 如果出现异常:
raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
解决办法:
将虚拟环境下lib/python3.7/site-package/django/db/mysql/bcakends/mysql/base.py中的`35、36`行注释后保存
2
query = query.decode(errors='replace') AttributeError: 'str' object has no attribute 'decode'
解决办法:
将虚拟环境下lib/python3.7/site-package/django/db/mysql/bcakends/mysql/operations.py中146行的query = query.decode(errors='replace')改成query = query.encode(errors='replace')
参考文件
[整合 Django + Vue.js 框架快速搭建web项目](https://cloud.tencent.com/developer/article/1005607)
关于项目部署的问题可以查看以上链接。