1. 路由系统, URL
1. url(r'^index/', views.index), url(r'^home/', views.Home.as_view()),
2. url(r'^detail-(\d+).html', views.detail),
3. url(r'^detail-(?P<nid>\d+)-(?P<uid>\d+).html', views.detail),
ps:
def detail(request, *args, **kwargs):
pass
实战:
a.
url(r'^detail-(\d+)-(\d+).html', views.detail),
def func(request,nid, uid):
pass
def detail(request, *args):
pass
def detail(request, *args):
pass
b.
url(r'^detail-(?P<nid>\d+)-(?P<uid>\d+).html', views.detail)
def func(request, nid,uid):
pass
def func(request, **kwargs):
kwargs = {'nid': 1, 'uid': 3}
def func(request, *args, **kwargs):
args = (2, 9)
4. name(作用:根据此名称生成自己想要的URL)
对URL路由关系进行命名,以后可以根据此名称生成自己想要的URL
url(r'^asdfasdfasdf/', views.index, name='i1'),
url(r'^yug/(\d+)/(\d+)/', views.index, name='i2'),
url(r'^buy/(?P<pid>\d+)/(?P<pid>\d+)/', views.index, name='i3'),
def func(request, *args,**kwargs):
from django.urls import reverse
url1 = reverse('i1') # asdfasdfasdf/
url1 = reverse('i2', args=(1,2)) # yug/1/2
url1 = reverse('i2', kwargs={'pid':1,'nid':9}) # yug/1/9
xxx.html
{% url "i1" %} # asdfasdfasdf/
{% url "i2" 1 2 %} # yug/1/2
{% url "i3" pid=1 nid=9 %} # yug/1/9
模板语言:
{% url "indexx" %}
{% url "indexx" 3 %}
# 注意:
# 当前的URL
request.path_info
2.视图
request.GET
request.POST
request.FILES
# checkbox等多选的内容
request.POST.getlist()
# 上传文件,form标签要做特殊设置
obj.request..FILES.get('fff')
obj.name
f = open(obj.name, mode='wb')
for item in obj.chunks():
f.write(item)
f.close()
4. FBV & CBV
function base view
url.py
index -> 函数名
view.py
def 函数(request):
...
===>
/index/ -> 函数名
/index/ -> 类
===>
建议:两者都用
3.模板
4.ORM操作
select * from tb where id >1
# 对应关系
models.tb.objects.filters(id__gt=1)
models.tb.objects.filters(id=1)
models.tb.objects.filters(id__lt=1)
1.Django请求生命周期
1.Django请求生命周期
-> URL对应关系 (匹配) -> 视图函数 -> 返回用户字符串
-> URL对应关系 (匹配) -> 视图函数 -> 打开一个HTML文件,读取内容
2. 创建django project
django-admin startproject mysite
'''
mysite
mysite
- 配置文件
- url.py
- settings.py
cd mysite
python manage.py startapp cmdb
mysite
mysite
- 配置文件
- url.py
- settings.py
cmdb
- views.py
- admin.py
- models.py # 创建数据库表
3,配置
模板路径
静态文件路径
# CSRF
4.编写程序
a.url.py
/index/ -> func
b.views.py
def func(request):
# 包含所有的请求数据
---
return HttpResponse('字符串')
return render(request,'index.html',{''})
return redirect('URL')
c.模板语言
return render (request, 'index.html', {'li': [11,22,33]})
{% for item in %}
<h1>{{ item }}</h1>
{% endfor %}
**********索引 ************
<h2> {{ item.0 }} </h2>
GET:
POST: