Login

Snippets by itavor

Snippet List

Admin actions as buttons instead of a menu [v2]

Add this to your admin change_list.html template to replace the actions drop-down with buttons. This is a rewritten version of snippet [1931](http://djangosnippets.org/snippets/1931/) with Django 1.3 compatibility and cleaner code. Thanks to [andybak](http://djangosnippets.org/users/andybak/) for the idea.

  • admin
  • actions
Read More

Custom managers with chainable filters

The Django docs show us how to give models a custom manager. Unfortunately, filter methods defined this way cannot be chained to each other or to standard queryset filters. Try it: class NewsManager(models.Manager): def live(self): return self.filter(state='published') def interesting(self): return self.filter(interesting=True) >>> NewsManager().live().interesting() AttributeError: '_QuerySet' object has no attribute 'interesting' So, instead of adding our new filters to the custom manager, we add them to a custom queryset. But we still want to be able to access them as methods of the manager. We could add stub methods on the manager for each new filter, calling the corresponding method on the queryset - but that would be a blatant DRY violation. A custom `__getattr__` method on the manager takes care of that problem. And now we can do: >>> NewsManager().live().interesting() [<NewsItem: ...>]

  • manager
  • queryset
Read More

itavor has posted 2 snippets.