Login

All snippets

Snippet List

Class Feeds DRY TemplateTag

I'm using the Django Feeds Framework and it's really nice, very intuitive and easy to use. But, I think there is a problem when creating links to feeds in HTML. For example: <link rel="alternate" type="application/rss+xml" title="{{ feed_title }}" href="{{ url_of_feed }}" /> Link's `HREF` attribute can be easily found out, just use `reverse()` But, what about the `TITLE` attribute? Where the template engine should look for this? Even more, what if the feed is build up dinamically and the title depends on parameters (like [this](http://docs.djangoproject.com/en/dev/ref/contrib/syndication/#a-complex-example))? This is the solution I came up with. However, as you can see, there is some caveats: * Requires Django 1.2 Class Feeds, don't know exactly how to do this with the old way of feeds. * If the feed class uses the request object, the `request` [context processor](http://docs.djangoproject.com/en/dev/ref/templates/api/#django-core-context-processors-request) must be configured, since `None` is passed if it isn't present in the context. * There's an oddity with Feed.__get_dynamic_attr(). The Feed subclass instance doesn't have this method; instead, it appears with another name. Don't know how to figure the name out at runtime... I've posted this problem on [StackOverflow](http://stackoverflow.com/questions/2784659/django-dry-feeds), but didn't get a better answer.

  • Feeds DRY templatetag HTML LINK
Read More

Generic CSV export admin action factory

**I've since made a better snippet for this: [#2995](http://djangosnippets.org/snippets/2995/)** based on [#1697](http://djangosnippets.org/snippets/1697/) This one is even more generic since you can specify which fields to include or exclude, a custom description text for the drop-down menu and whether to output the header row.

  • csv
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

CompressedTextField

I found my self doing data migration for a client, and also found that their old system (CSV) had 4 text fields that were 2 to 4MB each and after about 2 minutes of hammering the mysql server as I was parsing this and trying to insert the data the server would drop all connections. In my testing I found that if I didnt send those 4 fields the mysql server was happy to let me migrate all my data all (240GB of it). So I started thinking, "I should just store these fields compress anyways, a little over head to render the data, but thats fine by me." So thus was born a CompressedTextField. It bz2 compresses the contents then does a base64 encode to play nice with the server storage of text fields. Once I started using this my data migration, though a bit slower then without the field data, ran along all happy.

  • text
  • model
  • field
  • compress
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

SMTP sink server: prettier output

A modified version of the original SMTP sink server: [http://www.djangosnippets.org/snippets/96/](http://www.djangosnippets.org/snippets/96/). I've added some nicer, more verbose terminal messages.

  • email
  • debug
  • smtp
  • server
  • eml
Read More

Fake SSL Middleware for Tests and Local Development

Add `FakeSSLMiddleware` to the top of your `MIDDLEWARE_CLASSES` stack when running tests or developing locally to allow https:// links to operate correctly. Can be used in conjunction with other SSL middleware to allow critical tests to be performed.

  • middleware
  • ssl
  • testing
  • test
  • https
  • local
  • fake
Read More

Bitwise operator queryset filter

This snippet for django-1.2 allows you to use bitwise operators without using QuerySet.extra() from django.db.models import * from somewhere import FQ class BitWise(Model): type = CharField(max_length=8) value = IntegerField() def __unicode__(self): return '%s - %d' % (self.type, self.value) >>> BitWise.objects.create(type='django', value=1) <BitWise: django - 1> >>> BitWise.objects.create(type='osso', value=3) <BitWise: osso - 3> >>> BitWise.objects.create(type='osso', value=7) <BitWise: osso - 7> >>> BitWise.objects.filter(FQ(F('value') & 1, 'gt', 0)) [<BitWise: django - 1>, <BitWise: osso - 3>, <BitWise: osso - 7>] >>> BitWise.objects.filter(FQ(F('value') & 2, 'gt', 0)) [<BitWise: osso - 3>, <BitWise: osso - 7>] >>> BitWise.objects.filter(FQ(F('value') & 1, 'gt', 0) & Q(type='django')) [<BitWise: django - 1>]

  • filter
  • queryset
  • bitwise
  • operator
Read More

Improved User Admin

Helper function which adds some niceties to the auth/user admin views. Needs django 1.2 to work. ### Usage Define a UserProfile class and set `AUTH_PROFILE_MODULE` as per the [django docs](http://docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users) In your admin.py file (or anywhere else) add the following: from models import UserProfile from [path to snippet] import upgrade_user_admin upgrade_user_admin(UserProfile)

  • admin
  • user
  • userprofile
Read More

3109 snippets posted so far.