MARCH 03, 2010

Favorite Django Tips

TAGS: django, python, web,

A few months ago I found a really useful Stack Overflow Question. Here are my favorites from the answers.

Use render_to decorator instead of render_to_response

This decorator is found in the app django annoying, and is a very nice shortcut for declaring what template a view should render.

Instead of returning the response of render_to_response, you just return a python dict which will be used as the template context for the template specified as argument to the @render_to decorator. If anything else than a dict is returned, normal view processing will occur, so this won't break redirects or any other cases where you might return a HttpResponse (for example normal render_to_response code).

Anyway, here is an example on how to use it:

@render_to("list.html")
def list_posts(request):
    posts = BlogPost.objects.all()
    return {"blog_posts": posts}

This equals to:

def list_posts(request):
    posts = BlogPost.objects.all()
    return render_to_response('list.html',
        {'blog_posts': posts},
        context_instance=RequestContext(request))

Update (22/4): Marcin Nowak notified me that the render_to decorator breaks Django Reusable App converions, so I made a fork of django-annoying where I modified the render_to decorator to support template_name and extra_context keyword arguments.

Load custom template tags in all templates

Custom template tags that you use all over your templates can be auto loaded. Just add the following in a module that is loaded (i.e. your urlconf if you want the template tags to be loaded for the whole project)

from django import template
template.add_to_builtins('project.app.templatetags.custom_tag_module')

Use relative paths in settings.py

I hesitated about adding this tips, since I think it's quite obvious, but since so many people on Stack Overflow has voted it up, I guess there are people who use(d) absolute paths in their settings.py.

Don't use absolute paths in settings.py (i.e /home/jonatan/...), instead use relative paths so that the project will work wherever it resides.

import os.path
TEMPLATE_DIRS = (
    os.path.join(os.path.dirname(__file__), "templates"),
)

ABOUT ME

Jonatan Heyman My name is Jonatan Heyman, and I'm a programmer. On this blog I write about programming, the web and technology. I also listen to a large number of indie pop tunes. You can read more about me on the about page.

TAGS

MY LATEST TWEETS

Copyright (c) 2009-2010 Jonatan Heyman