Login

All snippets

Snippet List

Database Routing by URL

An example of how to select the "default" database based on the request URL instead of the model. The basic idea is that the middleware `process_view` (or `process_request`) function sets some context from the URL into thread local storage, and `process_response` deletes it. In between, any database operation will call the router, which checks for this context and returns an appropriate database alias. In this snippet, it's assumed that any view in the system with a `cfg` keyword argument passed to it from the urlconf may be routed to a separate database. Take this urlconf for example: `url( r'^(?P<cfg>\w+)/account/$', 'views.account' )` The middleware and router will select a database whose alias is `<cfg>`, or "default" if none is listed in `settings.DATABASES`, all completely transparent to the view itself.

  • multidb database router url
Read More

csrf_token for mako

Tag that can be used as `${ tags.csrf_token() }` in mako templates. Remember to import the tags namespace in your template, as such: <%namespace name="tags" module="my_app.tags"/>

  • mako csrf_token csrf
Read More

Detect iPhone & Switch Template via render_to_response

A fast way to implement an iPhone template switcher, especially if you have a lot of existing views using the render_to_response() shortcut. This checks for the iPhone browser and then modifies the chosen template by adding -mobile to the html's file name. Check out [this more complete list of user agents](http://minidetector.googlecode.com/svn/trunk/minidetector/tests/mobile_useragents.txt) if you need to detect specific mobile devices.

  • iphone template render_to_response
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

Mobile Device Middleware

Middleware class that checks the user agent against a known list of strings found in mobile devices, and if matched it then tries to determine the name of the template being rendered based on the convention of having every view use a keyword arg called "template". It then adds "mobile" to the template name and if the mobile template exists, it will override the "template" arg for the view with the mobile template name.

  • middleware
  • template
  • mobile
Read More

Real shuffle function

This function solve the issue of random.shuffle that is based only on randomized shuffling (that's not a real shuffling, because many times items returned aren't shuffled enough). This function make a randomized shuffle and after this loops long the list resorting to avoid two items with a same value in a given attribute. When shuffling is over and there are duplicates, they are leftover to the end (and you can remove them if you set 'remove_duplicates' to True) Run it in a separated file to see it in action.

  • shuffle
Read More

Capture Stack Trace Decorator

Put this decorator on any function to capture any exceptions generated within and print to a stack trace. example: @catch def my_func(): # code that may raise an exception here

  • decorator
  • debugging
Read More

Parsing Tag decorator

A simple decorator to register a template.Node object as a tag, without the need to write the usual "`token.split_contents()` yatta yatta blatta blatta" function. The decorator should be called with the name of the tag, and an optional `required` named argument in case your tag requires a minimum number of arguments. Please note that all the arguments in the templatetag call will be passed to the node (except the templatetag name and the `for` and `as` keywords) in the order given. Suggestions etc are very welcome, of course =)

  • templatetag
Read More

Filter by first letter inclusion tag

My first snippet ;] It's a simple inclusion tag for filtering a list of objects by a first letter using [django-filter](http://github.com/alex/django-filter) after having this "installed" you can use it in your template like this: {% load my_tags %} <div class="letter_filter"> Filter by first letter: {% letters_filter "MyNiceModel" %} </div> for information how to use django-filter in your view go to [docs](http://github.com/alex/django-filter/blob/master/docs/usage.txt) you should probably cache this inclusion tag since it makes 45 queries to the db (.count() > 0) Enjoy and improve ;] PS. some parts of this code are in Polish

  • filter django-filter inclusion tag first-letter
Read More

3109 snippets posted so far.