django 高级视图和URL配置

时间:2021-03-04 19:15:22

一、URL配置的多种方式比较

1.1 流线型化(Streamlining)函数导入
from django.conf.urls.defaults import *
from mysite.views import current_datetime, hours_ahead, hours_behind, now_in_chicago,
now_in_london
urlpatterns = patterns('',
(r'^now/$', current_datetime),
(r'^now/plus(\d{1,2})hours/$', hours_ahead),
(r'^now/in_london/$', now_in_london),
)
1.2 通过包含模块名和函数名的字符串

from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^now/$', 'mysite.views.current_datetime'),
(r'^now/plus(\d{1,2})hours/$', 'mysite.views.hours_ahead'),
(r'^now/in_london/$', 'mysite.views.now_in_london'),
)

使用多个视图前缀

旧的:

from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^/?$', 'mysite.views.archive_index'),
(r'^(\d{4})/([a-z]{3})/$', 'mysite.views.archive_month'),
(r'^tag/(\w+)/$', 'weblog.views.tag'),
)
新的:
from django.conf.urls.defaults import *
urlpatterns = patterns('mysite.views',
(r'^/?$', 'archive_index'),
(r'^(\d{4})/([a-z]{3})/$', 'archive_month'),
)
urlpatterns += patterns('weblog.views',
(r'^tag/(\w+)/$', 'tag'),
)


二、使用变量命名

2.1 对比

旧的:

urlpatterns = patterns('',
(r'^articles/(\d{4})/$', views.year_archive),
(r'^articles/(\d{4})/(\d{2})/$', views.month_archive),
)

新的:

urlpatterns = patterns('',
(r'^articles/(?P<year>\d{4})/$', views.year_archive),
(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', views.month_archive),
)

2.2 给URL传递第三个参数

urlpatterns = patterns('',
(r'^foo/$', views.foobar_view, {'template_name': 'template1.html'}),
(r'^bar/$', views.foobar_view, {'template_name': 'template2.html'}),
)
# views.py
def foobar_view(request, template_name):
m_list = MyModel.objects.filter(is_new=True)
return render_to_response(template_name, {'m_list': m_list})
这里的template_name就是URL模板里面第三个数据上字典中对应的参数


三、include 函数

 # project/news/urls.py  

urlpatterns = patterns('views',  

(r'^lastweek/$''lastweek'),  

  (r'^yesterday/$''yesterday'),  

(r'^today/$''today'),  

 )  

# project/urls.py   

urlpatterns = patterns('',  

    (r'^polls/$''polls.views.index')  

  (r'^news/', include('news.urls'),  

)  

注意:必须要在目录news下新建一个空文件__int__.py