不一样于其余语言的MVC模式,Django采用的是MVT模式,即Model、View、Template,这里的View其实质就是其余语言中的Controller(emmm.....),而Template其实就是html文件,因此原理其实大同小异,这里就很少赘述html
Django中的默认路由在项目主目录下的urls.py中,基本路由配置以下所示:python
from django.urls import path, include from . import views urlpatterns = [ path('articles/2003/', views.special_case_2003), path('articles/<int:year>/', views.year_archive), path('articles/<int:year>/<int:month>/', views.month_archive), path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail), path('', include('test.urls')) # 引入不一样应用的url配置 ]
以上为普通匹配方式,其中有几种可以限制路由中参数类型的函数能够使用。laravel
使用正则表达式匹配ajax
from django.urls import path, re_path from . import views urlpatterns = [ path('articles/2003/', views.special_case_2003), re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive), # ?P<year>意为指定参数的名字 re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive), re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<slug>[\w-]+)/$', views.article_detail), ]
URL起别名
此例相对于PHP laravel框架中的route()用法,具体用法以下正则表达式
# 路由中的配置 from django.urls import path, include from test import views urlpatterns = [ path('', views.index, name='test-index'), path('/<int:num>', views.getNum) path('', include('test.urls', namespace = 'test')) #为include起别名 ] # 在template中的运用 <a href="{% url 'test-index' 此处能够跟参数 %}"></a> # 在views中的运用 from django.http import HttpResponseRedirect from django.urls import reverse def redirect_to_year(request): year = 2006 # 参数 return HttpResponseRedirect(reverse('test-index', args=(year,)))
属性django
QueryDict对象
QueryDict对象定义在django.http.QueryDict,与python字典不一样,QueryDict类型的对象用来处理同一个键带有多个值的状况,能够经过方法get()
来获取值json
dict.get('键名',默认值) dict['键名']
另外还能够经过方法getlist()
将键的值以列表的形式返回浏览器
dict.getlist('键名',默认值)
属性缓存
方法cookie
重定向HttpResponseRedirect
from django.http import HttpResponse,HttpResponseRedirect def index(request): return HttpResponseRedirect('index/') # 反向解析 from django.core.urlresolvers import reverse def index(request): return HttpResponseRedirect(reverse('booktest:index2', args=(1,)))
返回json对象JsonResponse
from django.http import JsonResponse def index2(requeset): return JsonResponse({'name': 'abc'})
渲染模版render
from django.shortcuts import render def index(request): return render(request, 'booktest/index.html', {'h1': 'hello'})
重定向redirect
from django.shortcuts import redirect from django.core.urlresolvers import reverse def index(request): return redirect(reverse('booktest:index2'))
使用session
会话过时时间