- URLConf:负责url到view的map,就是一个urls.py module,通常在project和app级别都要定义,
#mysite/urls.py from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', url(r'^polls/', include('polls.urls')), url(r'^admin/', include(admin.site.urls)), ) #polls/urls.py from django.conf.urls import patterns, url from polls import views urlpatterns = patterns('', url(r'^$', views.index, name='index'),
#name是url的名字,可以在template中使用
url(r'^(?P<question_id>d+)/$', views.detail, name='detail'), ) - 首先根据setting.py中指定的ROOT_URLConf的值,本例是mysite.urls,django会load mysite.urls.py module
- django会发现’^polls/’与”/polls/34/”匹配,不管/polls/后面是id还是其他内容都匹配
- django会把”/polls/34/”中与regex匹配的字符串去掉,将剩下的”34/”传给polls.urls,与polls.urls中的regex匹配后会传参调用views.detail(request=<HttpRequest object>,question_id=’34’
- 每个Views.py中的函数都是一个view,view的职责包括:
- 返回HttpResponse对象,包含返回内容
- raise an exception,如Http404等
- Template:
- django的TEMPLATE_LOADERS包含很多loader,loader确定如何去查找template
- django的template可以都放在一个template目录下,但通常各个app的template都放到自己的路径下,路径为polls/templates/polls/index.html,index.html就是template文件,app_directories.loader会按照这个路径查找templat
- 示例模板:
#polls/templates/polls/detail.html <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }}</li> {% endfor %} </ul>
<li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> #使用这种方式更好,可以去掉hardcode, ‘detail’是在urls.py中定义的url的名字 <li><a href="{% url 'detail' question.id %}">{{ question.question_text }}</a></li>
- 为url指定名字空间,防止不同app的view同名
#mysite/urls.py from django.conf.urls import patterns, include, url from django.contrib import admin urlpatterns = patterns('', url(r'^polls/', include('polls.urls', namespace="polls")), url(r'^admin/', include(admin.site.urls)), ) #引用url时要加名字空间 <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
- 常用的函数:
- patterns(prefix,patterns):参数包含一个prefix和任意数量的url patterns,然会url patterns列表
- url(regex,view,kwargs,name):
- regex:匹配url的正则表达式
- view:regex匹配时,django会调用view,以HttpRequest对象作为第一个参数,regex捕获的其他匹配值作为其他参数。如果是simple capture,则值会按顺序依次传给view的函数,如果是named capture,值会作为keyword arguments
- kwargs:keyword arguments,kwargs存入字典再传给view,很少用
- name:给url命名
- include():引入URLConf
- render(request,templatepath,…):
- request:HttpRequest对象
- templaepath:template文件路径
- get_object_or_404(model,id): 如下代码等同
#效果等同 try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404 question = get_object_or_404(Question, pk=question_id)
- get_list_or_404():内部使用filter()函数而不是get()函数,list是空,rasie Http404