圆月山庄资源网 Design By www.vgjia.com

利用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是www.yourdomain/articles/2005/,则会匹配第二条规则,执行news.views.year_archive('2005').

注意点

域名部分会被过滤掉

articles的前面不需要添加/,因为前序url的末尾一定会有/

任何组匹配的变量,都会议字符串的形式传递给view, 虽然通过(\d{4})匹配出了2005,但2005任然会被当做字符串传递给year_archive

利用named group来传递参数

可以通过以下形式为特定的组指定一个名称.

urlpatterns = patterns('', 
 url(r'^articles/2003/$', 'news.views.special_case_2003'), 
 url(r'^articles/("htmlcode">
# URLconf 
from django.conf.urls import patterns, url 
 
urlpatterns = patterns('', 
 url(r'^blog/$', 'blog.views.page'), 
 url(r'^blog/page("1"): 
 # Output the appropriate page of blog entries, according to num. 

指定view前缀(提取公因式)

patterns函数的第一个参数即是view的前缀

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

指定多个view前缀

urlpatterns = patterns('myapp.views', 
 url(r'^$', 'app_index'), 
 url(r'^("htmlcode">
from django.conf.urls import include, patterns, url 
 
urlpatterns = patterns('', 
 # ... snip ... 
 url(r'^comments/', include('django.contrib.comments.urls')), 
 url(r'^community/', 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/("htmlcode">
from django.conf.urls import patterns, url 
 
urlpatterns = patterns('blog.views', 
 url(r'^blog/("htmlcode">
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的几种使用方式详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

标签:
Django,url

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com

稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!

昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。

这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。

而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?