安装及相关命令
# 命令方式:# 安装Django$ pip3 install django# 创建项目$ django-admin startproject 项目名# 创建应用$ python manage.py startapp app名# 启动$ python manage.py runserver [ip:port] # 默认是127.0.0.1:8000# 创建Admin 账号python manage.py createsuperuser# 也可使用PyCharm创建# 整合static文件# 1. 在settings.py中添加STATIC_ROOT = os.path.join(BASE_DIR, 'static')# 2. >> python manage.py collectstatic
uwsgi启动
uwsgi.ini文件
[uwsgi]# Django-related settings# the base directory (full path)chdir = /alidata/www/erpapi# Django's wsgi filemodule = erpapi.wsgi# the virtualenv (full path)home = %(chdir)/venv# process-related settings# mastermaster = true# maximum number of worker processesprocesses = 2# the socket (use the full path to be safesocket = 127.0.0.1:8084# ... with appropriate permissions - may be needed# chmod-socket = 664# clear environment on exitvacuum = true# 禁止记录请求日志disable-logging = true# 日志文件位置daemonize = %(chdir)/log/uwsgi.log# 日志文件最大20Mlog-maxsize = 20971520# uwsgi运行相关文件路径stats = %(chdir)/uwsgi.statuspidfile = %(chdir)/uwsgi.pid
uwsgi命令
# 启动./venv/bin/uwsgi --ini uwsgi.ini# 重新加载./venv/bin/uwsgi --reload uwsgi.pid# 停止./venv/bin/uwsgi --stop uwsgi.pid
Django目录
mysite |— manage.py 对当前Django程序所有操作 |— mysite |— settings.py Django配置文件 |— urls.py 路由系统 |— wsgi.py 用于定义Django用socket,wsgiref、uwsgi |— static 静态文件目录,手动创建,settings中配置 |— templates 模板目录 |— app01 app 目录 |— admin.py Django自带后台管理相关配置 |— models.py 写类,根据类创建数据库表 |— test.py 单元测试 |— views.py 业务处理,可以换成views目录
路由文件urls.py
# Django 1.xfrom django.conf.urls import urlurlpatterns = [ url(r'^index.html/?$', views.index),]# Django 2.xfrom django.urls import path, re_pathurlpatterns = [ path('index.html/', views.index), # django 2中 要用正则表达式则需要使用re_path]
request
request.method # 请求方式 POST GET ...request.POST # 用户POST提交的数据 dictrequest.GET # 用户GET提交的数据 dictrequest.path_info # 当前的url路径
视图返回
from django.shortcuts import HttpResponse, render, redirectreturn HttpResponse('返回内容')# 模块放在templates中,可在settings.py中修改配置return render(request, '模板文件.html', {...}) return redirect('url') # 跳转到指定url
配置
模板文件目录templates配置
# settings.py中配置 默认自动配置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', ], }, },]
静态文件目录static配置
# 在settings.py中配置STATIC_URL = '/static/' # 使用时前缀STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), # 时间目录名)
本地化配置
LANGUAGE_CODE = 'zh-hans' # 默认 en-us# 设置时区TIME_ZONE = 'Asia/Shanghai'# 国际化,多语言USE_I18N = True# 格式本地化USE_L10N = True# True TIME_ZONE设置无效为UTCUSE_TZ = False