Login

All snippets written in Python

Snippet List

Silently-failing include tag

This is the `local_settings.py` trick extended to Django templates. Sometimes you need to insert some arbitrary code in the HTML of the production site for external service integration like uservoice, typekit, google analytics... You don't want to put this code into source control because some other sites using the same source code may not need it. So, add this template tag to your collection and do: {% try_to_include 'head.html' %} And leave `head.html` out of source control. Then when you need to include some code on your production site, just add the `head.html` template with the desired code to include. I usually have one included template in the header for extra `<head>` tags, and one in the footer for extra javascript. Node that the included template is rendered against the current context. If the template doesn't exist, an empty string is returned. Also see the [full blog post](http://bruno.im/2009/dec/07/silently-failing-include-tag-in-django/) about this tag.

  • templatetag
  • include
  • silent
Read More

Drag and drop ordering of admin list elements using jQuery UI

Adds drag-and-drop ordering of rows in the admin list view. The only requirements is that the model has a field holding the position and that the field is made list_editable in the ModelAdmin. The changes of the ordering are applied after clicking 'Save'. The included javascript uses [jQuery UI's sortable](http://jqueryui.com/demos/sortable/) plugin Inspired by snippets [#1053](http://djangosnippets.org/snippets/1053) and [#998](http://djangosnippets.org/snippets/998/). Another similar snippet using AJAX is [#2047](http://djangosnippets.org/snippets/2047/).

  • admin
  • sort
  • jquery
  • order
  • sortable
Read More

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

Extended cacheable callables and properties

There are several snippets that provide a basic caching decorator for functions and methods (e.g. #202, #1130, etc.). The `Cacheable` class in this snippet extends them by (*if you don't see an unordered list below, the Markdown on this site is still broken...*): - Specifying how cache keys are determined in one of two general, flexible ways. - Exposing a few extra methods for (re)setting and deleting the cached value transparently. Given these methods, cache key management should follow DRY: keys are specified once (and only once) at instantiation time, without having to be repeated at later interactions with the cache. - Adding a variant for cacheable properties. Unlike some other snippets, the way cache keys are generated must be explicitly specified by the client; there is no automagic key generation for arbitrary `func(*args, **kwds)` calls (but can be added if desired). The reason is that all usual serialization approaches (`func.__name__`/`func.__module__`, `repr`, `pickle`, etc.) are generally fragile, unsafe, inefficient or all of the above. Explicit is better than implicit in this case.

Read More

Class-based coverage test runner

A coverage test runner that uses the class-based runner introduced with Django 1.2. Put it in your python path and add to your `settings.py`: TEST_RUNNER = 'path_to.CoverageRunner' COVERAGE_MODULES = [ 'blog.views', 'projects.views', 'middleware', ] Compatible with Django 1.2 and higher. You also need Ned Batchelder's `coverage.py` module (`pip install coverage`).

  • test
  • runner
  • coverage
Read More

Widget for CommaSeparatedIntegerField with pre-defined choices

Widget for editing CommaSeparatedIntegerField with a set of checkboxes. Each checkbox corresponds to single integer value. So, choices should be pre-defined for widget. **Example** Assume, we need a registration form for some event with time frame for 3 days, starting at Monday. User can select any of 3 days, so we need to show 3 checkboxes. Here's the basic example for such form: class EventRegistrationForm(forms.Form): days = forms.CharField(widget=NumbersSelectionWidget( ['Mon', 'Tue', 'Wed'], range(1, 4)))

  • forms
  • widget
  • comma-separated
Read More

Quiet runserver

It's quite common to use Django's `static.serve` functionality to serve media assets via the built-in development server. However, I always find that this is far too noisy - every asset produces a line of output on the console, and any debug messages I want to put there are hard to see. This management command monkey-patches the built-in `runserver` command so that it only generates a line of output for actual Django views - anything else is served as usual, but is not logged to the console. In fact the original version was already doing this for admin media, but not for your own media - I've just extended the logic. Put this in the management/commands directory of an installed app, saving it as (for example) `runserver_quiet`, then just do `./manage.py runserver_quiet` to run - it will accept all the same arguments as the built-in version.

  • runserver
  • management-command
Read More

Simple Class Based View Wrapper

After reading this article: http://blog.roseman.org.uk/2010/06/2/class-based-views-and-thread-safety/ and checking out this snippet: http://djangosnippets.org/snippets/2046/ I realized that I was using a class based view without even thinking about the consequences... so, without having to completely re-factor my existing class based views to make them singletons, I wrote this wrapper that should allow my class based views to work as I intended, and maintain state for a single request only.

  • class based views
Read More

icon shortcut - pseudohtml tag with attribute merging and variables resolving

A shortcut for generating img-s with predefined classes and attributes that mimics a html tag, while resolving context variables inside {% %} without crutches like tag/stuff/endtag. Used as `{% icon test class="spam" eggs="{{ object.pk }}" %}` yields `<img src="http://host.tld/media/icons/test.png" alt="" class="icon16 spam" eggs="42"/>`. Not customizable here for simplicity.

  • html
  • macro
Read More
Author: wiz
  • 0
  • 0

Ajax ordering models on the change list page of the admin using drag and drop with jQuery UI

Makes models orderable on the change list page of the admin using drag and drop with jQuery UI (via sortable()). So you can order your objects in more easy way. Inspired by snippets [#1053](http://djangosnippets.org/snippets/1053/) and [#998](http://djangosnippets.org/snippets/998/) First, ordering field to your model (default called 'order). You can specify other name for this field, but you should add 'order_field' attr to model (i.e order_field = 'your_new_order_field_name') Also, snippet adds 'order_link' field to admin's changelist and hides it by javascript.

  • ajax
  • admin
  • jquery
  • ordering
Read More

My approach on class based views

By using __new__ the result of a class instantiation is not an object but the result of a method call. This way classes can be used for views the same way as functions.

  • class based views
Read More

Overwriting file storage

Useful if you can make sure your files will never collide unless they share the same contents. You point to the storage parameter when you declare an ImageField and use the hashed_path class method (seemed to make sense to bundle it with the class) to build a custom upload_to method that has to generate the path based on the file contents. Combining both will allow you to deduplicate files uploaded repeatedly.

  • file storage
Read More

Dynamically alter the attributes of a formset

Allow you to specify a "General case formset/modelformset" and then alter the attributes of that formset, specificly: extra, can_order, can_delete and max_num. So you specify: >>> formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O')) and then you want to dynamically add multiple fields with javascript and save the new ones. By default a formset only has 1 extra field. With this you can return a new formset (using the same queryset, forms, formset base class, etc) but with different attributes. So you could then add 10 extra fields if the user added 10 new forms.

  • dynamic
  • formset
  • attributes
Read More

Limit queryset to objects related to parent in ManyToMany fields within admin inlines

`formfield_for_manytomany` allows you to limit the choices/queryset for a ManyToManyField, but without direct access to the parent object. This snippet stores a reference to the parent object in `get_formset` and allows limiting of `ManyToManyField`s to objects related to the same parent object. See `ExampleInline` for example usage. If for some reason you have a `ManyToManyField` in a `TabularInline`, just change the `template` in the subclass.

  • limit_choices_to ManyToMany ManyToManyField admin inline formfield_for_manytomany
Read More

2955 snippets posted so far.