1.准备
1.1 新建虚拟环境
mkvirtualenv -p /usr/bin/python3 mydj
进入虚拟环境 workon
退出虚拟环境 deactivate
删除虚拟环境 rmvirtualenv mydj
1.2 安装django
pip install django
1.3 新建django项目
django-admin startproject mydjango
项目目录
manage.py 命令行工具,管理django项目
init.py 表示该目录是python包
setting.py 配置文件
urls.py 配置网址
wsgi.py 部署
1.4 启动项目
python manage.py runserver 0.0.0.0:8000
setting.py中
ALLOWED_HOSTS=['*']
2.编辑
2.1 新建APP
python manage.py startapp book
2.2 创建视图函数
在book文件夹中views.py中
from django.http import HttpResponse
def hello(request):
return HttpResponse("hello")
2.3 通过url传递变量
在url.py文件中
path('hello/<name>/',views.hello_name)
在book文件夹中views.py中
from django.http import HttpResponse
def hello_name(request,name):
return HttpResponse("hello %s" %name)
2.4 转换器
在url.py文件中
path('hello/<int:name>/',views.hello_name)
str 不包含路径分隔符的字符串
int 数字
slug 匹配字母,数字,以及横杠,下划线
path 非空字符串,包含路径分隔符
uuid
2.5 url中的正则
在url.py文件中
re_path(‘hello/(正则表达式)/’,view.hello)
2.6 url的分配----include方法
在APP中新建urls.py
在主目录urls.py中
from django.urls.import include
path('book/',include('book.urls'))
在APP的urls.py中
from django.urls import path
from . import views
urlpatterns=[
path('index/',views.index)
]
在views.py中新建index视图函数
2.7 不定长参数kwags的传参
在urls.py中
path('book/',view.hello,{"switch":"true"})
在views.py中
def index(request,**kwargs)
if kwargs.get(‘switch’)== “true”:
return redirect (‘book/article_new/’)
2.8 name参数
给path取名字
return redirect(reverse(‘name’))
3 模板渲染
新建与APP同级的templates文件夹,在templates中新建与APP同名的文件夹
3.1 配置模板文件目录
在setting.py中
TEMPLATES:
“DIRS”:[os.path.join(BASE_DIR,‘templates’)]
3.2 通过get_template方法实现模板渲染
from django.template.loader import get_template
def index(request,**kwargs):
t=get_template(‘book/index.html’)
html=t.reder()
return HttpResponse(html)
3.3 直接通过render方法实现模板渲染
from django.shortcuts import render
def index(request,**kwargs):
return render(request,‘book/index.html’)
3.4 传参
def index(request ,name,**kwargs):
return render(request,‘book/index.html’,context={‘name’:name})
模板html中使用{{name}}获取参数