Login

All snippets

Snippet List

render_to_response wrapper

Simplifies using RequestContext in render_to_response. Simply call the wrapper with request as the first argument, and the rest of the arguments are as normal for render_to_response. ex: render_response(request, 'foo_list.html', {'foo': Foo.objects.all()})

  • render_to_response
  • requestcontext
  • shortcut
  • template
Read More

Using manager methods

This is part of the user-registration code used on this site (see [the django-registration project on Google Code](http://code.google.com/p/django-registration/) for full source code), and shows a couple of interesting tricks you can do with manager methods. In this case there's a separate `RegistrationProfile` model used to store an activation key and expiration time for a new user's account, and the manager provides a couple of useful methods for working with them: `create_inactive_user` creates a new user and a new `RegistrationProfile` and emails an activation link, `activate_user` knows how to activate a user's account, and `delete_expired_users` knows how to clean out old accounts that were never activated. Putting this code into custom manager methods helps a lot with re-use, because it means that this code doesn't have to be copied over into different views for each site which uses registration, and also makes more sense in terms of design, because these are methods which need to "know about" the model and work with it, and so they belong in a place close to the model.

  • managers
  • registration
Read More

Fetching top items

This is a method from the custom manager for the Snippet model used on this site; the basic idea is to be able to ask for the top `n` "foo", where "foo" is something related to Snippet. For example, you can use `top_items('tag')` to get the top Tags ordered by how many Snippets are associated with them. I have a feeling that I could get this down to one query, but haven't yet put in the time for it.

  • snippets
  • sql
  • managers
  • group-by
Read More

3109 snippets posted so far.