1.开发环境
1.系统:
Windows7
2.开发工具:
pycharm
3.python版本:
3.6
4.数据库:
MySQL
5.框架:
django2.0
2.新建django项目qr
3.整理目录
1.新建app
python manage.py startapp user_operations
python manage.py startapp good
2.新建目录
apps 存放app
extra_apps 存放第三方包
static/images、css、js、存放静态文件
media 存放媒体文件
4.新建数据库qr
1.新建数据库
打开mysql终端:
show databases; --查看所有数据库 create database qr default character set utf8 collate utf8_general_ci; --创建数据库qr,因为创建数据表内有中文字段,所以要加default show databases; --查看所有数据库
2.连接数据库
1.在settings.py中:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'qr', 'USER':'root', 'PASSWORD':'数据库密码', 'HOST':'127.0.0.1', "OPTIONS":{"init_command":"SET default_storage_engine=INNODB;"}#第三方登录功能必须加上 } }
2.安装PyMYSQL:
pip install PyMYSQL
3.在qr/qr/__init__.py中加代码:
import pymysql pymysql.install_as_MySQLdb()
4.在pycharm直接操作数据库:
jdbc:mysql://localhost:3306/qr?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
5.配置
1.Mark一下apps和extra_apps:
2.在settings.py中:
1.配置目录路径:
import sys sys.path.insert(0,BASE_DIR) sys.path.insert(0,os.path.join(BASE_DIR,'apps')) sys.path.insert(0,os.path.join(BASE_DIR,'extra_apps'))
2.配置静态文件和媒体文件路径:
STATIC_URL = '/static/' # STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) MEDIA_URL='/media/' MEDIA_ROOT=os.path.join(BASE_DIR,'media')
'django.template.context_processors.media'
3.注册app:
'good.apps.GoodConfig', 'user_operations.apps.UserOperationsConfig'
3.在qr/qr/urls.py中:
from django.contrib import admin from django.urls import path from django.views.static import serve from qr.settings import MEDIA_ROOT urlpatterns = [ path('admin/', admin.site.urls), path('media/<path:path>',serve,{'document_root':MEDIA_ROOT}), ]
6.新建首页
1.在templates目录下新建index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 首页 </body> </html>
2.在qr/qr/urls.py中:
from django.contrib import admin from django.urls import path,include from django.views.static import serve from qr.settings import MEDIA_ROOT from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('media/<path:path>',serve,{'document_root':MEDIA_ROOT}), path('', TemplateView.as_view(template_name='index.html'), name='index'), ]
运行项目: