对Django url的几种使用方式详解

时间:2021-05-22

利用Django开发网站,可以设计出非常优美的url规则,如果url的匹配规则(包含正则表达式)组织得比较好,view的结构就会比较清晰,比较容易维护。

最简单的形式

<code> from django.conf.urls import patterns, url urlpatterns = patterns('', url(r'^articles/2003/$', 'news.views.special_case_2003'), url(r'^articles/(\d{4})/$', 'news.views.year_archive'), url(r'^articles/(\d{4})/(\d{2})/$', 'news.views.month_archive'), url(r'^articles/(\d{4})/(\d{2})/(\d+)/$', 'news.views.article_detail'), )</code>

其中,正则表达式中组匹配出来的结果可以作为positional parameters传递给view.

如果url是munity/', include('django_website.aggregator.urls')), url(r'^contact/', include('django_website.contact.urls')), # ... snip ... )

当然也可以直接include其它patterns

from django.conf.urls import include, patterns, url extra_patterns = patterns('', url(r'^reports/(?P<id>\d+)/$', 'credit.views.report'), url(r'^charge/$', 'credit.views.charge'), ) urlpatterns = patterns('', url(r'^$', 'apps.main.views.homepage'), url(r'^help/', include('apps.help.urls')), url(r'^credit/', include(extra_patterns)), )

为view函数传递额外参数

from django.conf.urls import patterns, url urlpatterns = patterns('blog.views', url(r'^blog/(?P<year>\d{4})/$', 'year_archive', {'foo': 'bar'}), )

直接使用view函数

from django.conf.urls import patterns, url from mysite.views import archive, about, contact urlpatterns = patterns('', url(r'^archive/$', archive), url(r'^about/$', about), url(r'^contact/$', contact), )

以上这篇对Django url的几种使用方式详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章