Snippet List
Sometimes you have context variables that are needed on many pages in a site, but not all. You only want them to be evaluated when actually needed, especially if they are expensive calculations that do DB queries etc. The pattern to use is shown: put a callable into the context, not the final value, and also wrap the callable with memoize_nullary.
- template
- contextprocessor
- lazy
- context-processor
- memoize
If you've ever wanted to dynamically lookup values in the template layer (e.g. `dictionary[bar]`), then you've probably realized/been told to do this in the python layer. The problem is then you often to build a huge 2-D list to hold all of that data.
These are two solutions to this problem: by using generators we can be lazy while still making it easy in the python layer. I'm going to write more documentation later, but here's a quick example:
from lazy_lookup import lazy_lookup_dict
def some_view(request):
users = User.objects.values('id', 'username')
articles = Article.objects.values('user', 'title', 'body')
articles = dict([(x['user'], x) for x in articles])
return render_to_response('some_template.html',
{'data': lazy_lookup_dict(users, key=lambda x: x['id'],
article=articles,
item_name='user')})
Then in the template layer you'd write something like:
{% for user_data in data %}
{{ user_data.user.username }}, {{ user_data.article.title }}
{% endfor %}
- template
- dynamic
- lookup
- lazy
- dynamic-lookup
Since the decorators of your views are evaluated during parsing urls.py you have an 'chicken - egg' problem. The method reverse() can't be used since urls.py is not read.
This snippets evaluates reverse() lazy.
[Related ticket: 5925](http://code.djangoproject.com/ticket/5925)
Django 1.4 (current trunk) has a lazy reverse.
4 snippets posted so far.