Login

Most bookmarked snippets

Snippet List

Modeli18n

This is a Model base class used to support internationalization (i18n) for your models. This code extends the Django's Model class so you can use all available options from Model safely. Basicly, it uses introspection to create a sub-model to your model to hold translation. **Features:** 1. Simplicity of use. You simply extend your model with this class and add all the fields that needs to be translated are placed under the `locale` sub-class; 2. The code uses the `django.utils.translation.get_language()` to select the current language; 3. You can use `python ./manage.py syncdb` command safely; 4. Force the user to enter a translation for each language even if the fields can be blank. This makes sure that all objects are returned safely. **Ordering by locale fields:** To sort on translated fields, use the form of "model_i18n__transfieldname" (see code for example). **Limitation:** Do not use localized fields in __unicode__, the admin will throw an exception when you'll add a new item and do "save and continue". Just drop a comment if you need more information. (last update: 06/15/2010)

  • internationalization
  • i18n
  • model
  • locale
  • translation
  • culture
Read More

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

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

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

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

strip_tags like php one

Usage: `clean_html = strip_tags(html, {'a': ['href'], 'p': ['class']})` Based on [another snippet](http://www.djangosnippets.org/snippets/205/).

  • tags
  • html
Read More

ISBN model field: displays 10- and 13-digit variants and external links

Requires [PyISBN](http://pypi.python.org/pypi/pyisbn/0.5.2). Use like so: class Book(models.Model): title = models.TextField() isbn = ISBNField() ... the link in the widget can be changed to amazon, borders, you name it. If the DB version is a 13-digit ISBN, the display box contains the 10-digit, labeled; and vice-versa.

  • django
  • model
  • python
  • widget
  • modelfield
  • isbn
  • books
Read More

Partial templates, combine with and include

This snippet adds simple partial support to your templates. You can pass data to the partial, and use it as you would in a regular template. It is different from Django's {% include %}, because it allows you to pass a custom variable (context), instead of reusing the same context for the included template. This decouples the templates from each other and allows for their greater reuse. The attached code needs to go into templatetags folder underneath your project. The usage is pretty simple - {% load ... %} the tag library, and use {% partial_template template-name data %} in your template. This will result in template passed as template-name to be loaded from your regular template folders. The variables are passed in a with compatiable syntax, eg. VAR as NAME and VAR as NAME No limitations on the number of variables passed.

  • template
  • templates
  • partial
  • with
  • include
  • partials
Read More

Custom model field to store dict object in database

**Disclaimer** This is proof of concept snippet, It can not be considered as best practice. Seems like it's better to store (key => value) in sepetare model with 'key' and 'value' fields. **Example** You can assign any dict to model field that can be dumped/serialized with Django json encoder/decoder. Data is saved as TextField in database, empty dict is saved as empty text. Tested with Django 1.2beta. import DictionaryField class UserData(models.Model): user = models.ForeignKey(User) meta = DictionaryField(blank=True) There are similar snippets: [JSONField 1](http://www.djangosnippets.org/snippets/377/) or [JSONField 2](http://www.djangosnippets.org/snippets/1478/).

  • models
  • fields
  • json
Read More

Yet Another Image Resizer

There's a whole range of examples online for resizing images in Django some of which are incredibly comprehensive with a wide variety of options. Here's my take on the task that serves as a simple drop in for when you don't want to include a separate app. - Only generates the resized image when first requested. - Handles maintaining proportions when specifying only a width or a height. - Makes use of PIL.ImageOps.fit for cropping without reinventing the wheel.

  • template
  • tag
  • image
  • pil
  • thumbnail
  • resize
Read More

send_mail wrapper with DEBUG email trapping

By using this simple wrapper instead of Django's default send_mail function, you gain the peace of mind of knowing that when settings.DEBUG == True, all the emails will be sent to you instead of the original recipient. Handy for testing.

  • email
  • debug
  • testing
  • mail
  • intercept
  • trap
Read More

3110 snippets posted so far.