Login

Snippets by coleifer

Snippet List

Generic Autodiscovery

Admin-like autodiscover for your apps. I have copy/pasted this code too many times...Dynamically autodiscover a particular module_name in a django project's INSTALLED_APPS directories, a-la django admin's autodiscover() method.

  • autodiscover
Read More

Generating aggregate data across generic relations

http://github.com/coleifer/django-generic-aggregation http://charlesleifer.com/blog/generating-aggregate-data-across-generic-relations/ Generate and calculate aggregations across generic foreign keys. >>> from misc import generic_annotate, generic_aggregate >>> from blog.models import Entry >>> from tagging.models import TaggedItem >>> from django.db.models import Count >>> qs = generic_annotate(Entry.objects.all(), TaggedItem.object, 'id', Count) >>> qs[0].score 5L >>> qs[1].score 4L >>> qs[1].tags u'databases django many-to-many python' >>> generic_aggregate(Entry.objects.all(), TaggedItem.object, 'id', Count) 106L # total number of times entries were tagged

  • django
  • gfk
  • aggregation
Read More

Call a manager method on any model with a filter

Often I want to call a custom manager method in the template, something like Snippet.objects.get_latest(). I hate writing custom templatetags to do all that work, so instead I've written a filter that will work for any. Here's how I use it: {% for snippet in "cab.snippet"|call_manager:"top_rated"|slice:":5" %}

  • template-filter
Read More

Use memcached to throttle POSTs

### Problem: you want to limit posts to a view This can be accomplished with a view decorator that stores hits by IP in memcached, incrementing the cached value and returning 403's when the cached value exceeds a certain threshold for a given IP.

  • cache
  • decorator
Read More

Latest instances template filter

Writing templatetags is obnoxious. Say you have a small blurb on all your pages that shows the latest 5 comments posted to the site -- using this filter, you could write the following: {% for comment in "comments.comment"|latest:5 %} ...display comment here... {% endfor %}

  • template
Read More

Cached template filters

Say you'd like to cache one of your template filters. This decorator acts sort of like memoize, caching a result set based on the arguments passed in (which are used as the cache key).

  • template
  • cache
Read More

assertQuerysetEqual

I often find myself testing that the queryset returned by a method contains the instances I expect. I use a custom method, **assertQuerysetEqual()**, to test the equality of two querysets or lists:: def test_some_values(self): qs = get_user_list() self.assertQuerysetEqual(qs, [normal_user, super_user]) Makes it easy to test small querysets against lists whose values are known and expected.

  • testing
  • test
Read More

coleifer has posted 11 snippets.