锁定老帖子 主题:Django中的URL配置和模板
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2010-01-23
最后修改:2010-01-23
Django中的URL配置 :
实例:
urlpatterns = patterns('', # Example: # (r'^myweb/', include('myweb.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: (r'^admin/', include(admin.site.urls)), (r'^$',"view.index"), (r'^hello/$',"view.hello"), (r'^time/(\d+)/$',"view.time"), (r'^time1/(?P<id>(\d+))/$',direct_to_template,{"template":"time1.html"}), (r'^time2/$',direct_to_template,{'template':'time2.html'}), )
(r'^$',"view.index"), (r'^hello/$',"view.hello"),
(r'^time/(\d+)/$',"view.time"), 访问http://localhost/time/1/,http://localhost/time/2/这样的地址,后面(\d+)用于匹配的数字,非数字是必能匹配的,并且后面的(\d+)的值会作为参数,所以方法应该这样写
def time(request,offset) request为请求对象会自动传递进来,offset即为URL中(\d+)匹配的值,比如http://localhost/time/2/,offset 的值就是2
(r'^time1/(?P<id>(\d+))/$',direct_to_template,{"template":"time1.html"}), direct_to_template:为转发模板到 time1.html (?P<id>(\d+)) 表示匹配后给这个参数加上一个别名,在页面中使用{{params.id}}可以访问到URL中id的值
另外在加载模板的时候需要配置: 1、settings.py 中的
TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(os.path.dirname(__file__), 'templates/').replace('\\','/'), ) 表示将网站目录下 templates/的模板路径
2、在urls.py中导入direct_to_template方法 from django.views.generic.simple import direct_to_template
如何启用Django的admin,我用的是1.1.1版本:
1、 在setting.py中启用admin和auth INSTALLED_APPS = ( ) 2、在urls.py中启用以下代码: # Uncomment the next two lines to enable the admin: url配置 (r'^admin/', include(admin.site.urls)), 启用
就能打开admin,比如http://localhost/admin/
命名匹配:
在 Python 正则表达式里, 命名分组的语法是 (?P<name>pattern), 这里 name 是分组的名字而 pattern 是要匹配的模式. 下面用命名分组重写上面的例子: urlpatterns = patterns('', (r'^articles/2003/$', 'news.views.special_case_2003'), (r'^articles/(?P<year>\d{4})/$', 'news.views.year_archive'), (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/$', 'news.views.month_archive'), (r'^articles/(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d+)/$', 'news.views.article_detail'), ) 上面的代码与前面的代码功能完全相同, 不过传递给 view 函数的不再是位置相关参数,而变成了关键字参数.比如:
方法定义: def month_archive(request,year) def month_archive(request,year,month) def article_detail(request,year,month,day)
实际上, 这意味着 URLconfs 更清晰,而且避免了参数顺序错误引发的 bug -- 定义 view 函数时不必特别在意参数的顺序.当然有些开发人员认为命名分组的语法很丑并且繁琐
声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
浏览 6288 次