Django URLConf 的几个tips学习笔记


Django URLConf 的几个tips学习笔记

Published on Sat 04 Apr 2009 10:04 ( 11 months, 1 week ago)
Django 学习

1. URLConf tips and tricks

named URL patterns:

url(r'^weblog/$', 'django.views.generic.date_based.archive_index', info_dict, name='weblog_index'),

and then be able to drop calls in your templates like

{% url weblog_index %}

在URLConf中decorate view有些时候比在view中写定更灵活:


you can decorate it right there in the URLConf:

url(r'^weblog/$', login_required(date_based.archive_index), info_dict, name='weblog_index'),

This is extremely powerful, for two reasons:


  1. It lets you decide, on a per-URL basis, whether to decorate a particular view function, which improves the reusability of your views.
  2. It provides an easy way to decorate generic views without having to write a decorated wrapper function around them.


comments中有一个有价值的tips:


Another way of getting around the cached-queryset-in-extra-context thing: any items in extra_context that are callables will be called each time through the view. This means you can do:



def latest_link():
return Link.objects.latest()

extra_context = {‘latest_link’: latest_link}

or, more simply:

extra_context = {‘latest_link’: lamba: Link.objects.all() }

or even:

extra_context = {‘latest_link’: Link.objects.latest }


 

2. Django Tip: HTTP verb dispatching

http://www.djangosnippets.org/snippets/436/

简单来说就是在urlconf里做文章,写一个decorator来区分不同的http verb:


handlers = {
'DELETE': delete_view,
'PUT': creation_view,
'__default__': normal_view,
}

urlconf = patterns('',
('/my/url/pattern/', MethodDispatcher(handlers), ...),
...
)


其中提及的REST interface framework for Django感觉也颇有价值。


Related posts:


Search related in web:

Custom Search

RSS Feed

One click subscribe this blog in your google reader!

Be social!


Want to say something here? please sign in



Blog posts link to this page
What are friends tweeting?
Tags cloud
Monthly Archives