第二章Djangos视图和URL配置

来源:互联网 发布:午夜tv的软件 编辑:程序博客网 时间:2024/06/05 02:04

第二章Djangos视图和URL配置(MVC-根据URL配置后台调用Controller)

DjangoURL配置背后的哲学: 松耦合原则。因为url和视图文件是分离的。

Urls.py中url方法的设置:

Url方法: 多参数可以让我们创建一复用的抽象方法:

参数1-是正则表达式url地址(如r'^blog/index');

参数2-是其对应的方法相对地址(从project下)或对象(先导入views包);

参数3-参数

url方法参数2:使用字符串

注释:根目录http://127.0.0.1:8000/会报404错,添加视图时使用URL模式`^$` , 代表一个空字符串,如“('^$', my_homepage_view),”。

基于project的相对地址:参数2是其对应的方法相对地址(如’app_name.views.method_name’)。

基于patterns第一个参数的相对地址:设置patterns方法的第一参数设为相对地址,参数2是其对应的方法名字(如patterns(' app_name.views ',和url参数2为’method_name’)。

url方法参数2:使用对象(非字符串)

 

先导入views包

import blog.views import index

参数2是其对应的方法的对象(如index)。

url方法三

注释:如果你有多个前缀,就用

urlpatterns = patterns('mysite.views', …

urlpatterns += patterns('mysite.views', …

 

那系统自动找:patterns第一参数 “\”方法名字.

Debug模式:临时修改URLconf。

注释:URL链接/debuginfo/ 只在你的 DEBUG 配置项设为 True 时才有效。

if settings.DEBUG:

    urlpatterns += patterns('',

        (r'^debuginfo/$', views.debug),

pattern有多个参数,视图参数会当做另一个参数。如果url有同名命名参数,会被参数覆盖。


应用:多url指向同一处理方法。

  (r'^mydata/birthday/$', views.my_view, {'month': 'jan', 'day': '06'}),

  (r'^mydata/(?P<month>\w{3})/(?P<day>\d\d)/$', views.my_view),

# urls.py

urlpatterns = patterns('',

    (r'^foo/$', views.foobar_view, {'template_name': 'template1.html'}),

 

# views.py

def foobar_view(request, template_name):

URL涵盖多个项目:

就像添加admin站点一样,用include函数。
注释:总url的参数会传到子站点url里面去。

 (r'^photos/', include('mysite.photos.urls')),

 

返回HTML-HttpResponse方法:

views.py中index方法中返回HTML字符串。还可以用对象render_to_response来调用模板文件。

方式一:纯字符串

from django.http import HttpResponse

HttpResponse  “<html><head>hi Django</head></html>”

#或HttpResponse  “hi Django”

方式二: 用Template方法传参数

 

from django.template import Template, loader, Context

t = Template(“<head>hi Django</head>”)

#或t = loader.get_template('index1.html')

contextObj = Context({}) #privode the data

return HttpResponse(t.render(contextObj))

 

URL路径中参数传递的2种方式:

Url参数(url路径的一部分)的命名是基于正则表达式,规则为“(?P<name>pattern)”,分为命名组和非命名组2种方式。命名组和非命名组是不能同时存在于同一个URLconf的模式中。

HTTPget方法,url后面加参数

?var=value(&var2=value2)

方法一:命名组法,如id

 

 

 

关键字参数法:

urls.py文件:

url(r'^blog/index/(?P<id>\d{2})/$', 'index')

views.py文件:

def index(req, id):

方法二:非命名组法,即位置法。

位置/匿名参数法:

urls.py文件:

url(r'^blog/index/(\d{2})/$', 'index')

views.py文件:

def index(req, anyName):

 

其他参考:

1:如果你是喜欢URL都以’/’结尾的人(Django开发者的偏爱),可设置”APPEND_SLASH””True”.如果不喜欢URL以斜杠结尾或者根据每个URL来决定,那么需要设置”APPEND_SLASH””False”.

2:查看Python方法import搜索路径的值:importsys; print sys.path。

 

0 0
原创粉丝点击