Login

Top-rated snippets

Snippet List

"Autoconnect" model decorator, easy pre_save and post_save signal connection

This method allows you to define pre_save and post_save signal connections for your decorators in a little more clean way. Instead of calling `pre_save.connect(some_func, sender=MyModel)`, or perhaps `pre_save.connect(MyModel.some_static_func, sender=MyModel)`, you can simply define the pre_save method right on your model. The @autoconnect decorator will look for pre_save and post_save methods, and will convert them to static methods, with "self" being the instance of the model.

  • pre_save
  • post_save
  • signal-connect
Read More

Middleware to move tags <script> to the bottom

This middleware makes the page load faster because it moves all tags <script> to the end of document. When a tag <script> loads, it blocks parallel loading, so, the best practice is load them after load CSS and images. To use it, just put in a file and add to your setting MIDDLEWARE_CLASSES.

  • performance
  • script
  • otimization
Read More

Aggregation class "Count" with Case

Use it like below: totals = MyClass.aggregate( is_enabled_yes=CountCase('is_enabled', when=True), is_enabled_no=CountCase('is_enabled', when=False), count_if=CountCase('id', case="another_field in ('a','b')", when=True), )

  • count
  • annotate
  • aggregation
Read More

While loop template tag

The missing `while` template tag. Built on top of http://djangosnippets.org/snippets/2093/, it also supports `break` and `continue` out of the box.

  • template
  • templatetag
  • loop
  • while
Read More

Image model with thumbnail

A relatively simple Photo model which generates its own thumbnail when saved. A default size is specified as `thumb_size` in the `save()` arguments. Other thumbnailing strategies don't save the thumbnail dimensions, and since the actual dimensions of the thumbnail created by PIL's `thumbnail` method are somewhat non-deterministic, it is difficult to create an `img` tag with proper height and width attributes. This approach makes that task simple. This approach works well if only one thumbnail size is required. It could easily be adapted to support two or three thumbnail sizes, but adding more sizes would quickly get unwieldy. This was adapted from http://biohackers.net/wiki/Django1.0/Thumbnail

  • image
  • thumbnails
  • thumbs
Read More

Get actual child model in multi-table inheritance

A common problem (it hit the Django mailinglist a couple of times) is that if you get `models.Topping.objects.all()`, you get a list of toppings, although they stand for other classes such as `SalamiTopping` or `CheeseTopping`. If you need the actual object, just derive `Topping` from `PolymorphicModel`, and say `topping.actual_instance`. This will give you e.g. a `SalamiTopping`. Sometimes you just want to check for the actual class. You can get it by saying `topping.content_type.model_class()`. There is a slight performance impact when creating objects because they have to be saved twice. NEWS: A good alternative to this approach is the [InheritanceManager](https://github.com/carljm/django-model-utils/blob/master/README.rst).

  • models
  • child-model
  • multi-table-inheritance
  • polymorphy
Read More

Number generator to autofill a field

**Number format:** number/year **Purpose:** When the user adds a new bill, the "number" field will be automatically filled with the appropriate number. * The snippet automatically increments the bill number based in the highest number available. This is because in the use case, the user could start by *any* number, and we couldn't use the PK number (p.e. if the user first object number is 324/10, using the PK will convert it to 1/10) **NOTE:** bill_type is a Boolean value to mark if the bill is outgoing or ingoing. Since we only need to mark the outgoing ones, we filter through this field.

  • django-admin
  • number-generator
  • autofill
Read More

Multiple Select Widget with jQueryUI

This widget can be imported in your forms.py file and used like so: formfield = forms.ModelMultipleChoiceField(widget=MultiSelectWidget, queryset=Model.objects.all()) The javascript is provided by [Michael's Multiselect](http://github.com/michael/multiselect/tree/next). In addition to the javascript you will need [jQuery (the latest release is fine) and jQuery UI](http://jqueryui.com/). The convenient thing is that this widget will style to match whichever jQuery UI you've 'rolled' or selected, making it highly customizable! Hopefully this helps others who wanted a nice widget with jQuery and were sad to find there were no nice default options, enjoy! :)

  • jquery
  • widget
  • multiple select
  • multiselect
  • jqueryui
Read More

django subdomain support for both resolve and reverse.

Add these two middleware to the top of MIDDLEWARE_CLASSES. Add BASE_DOMAIN to your setting file : BASE_DOMAIN = '.13.com'. your root urlconf may like this: urlpatterns = patterns('', url(r'^www:(?P<id>[0-9]+)/$', 'couponcn.store.views.site_index', name='site_index'), url(r'^news:abc/def/$', 'couponcn.store.views.site_index', name='site_index2'), ) then {% url site_index id=4 %}<br /> {% url site_index2 %} in your template or the reverse function will work out urls like this: http://www.13.com/4/ http://news.13.com/abc/def/

  • url
  • reverse
  • resolve
  • subdomain
Read More

load m2m fields objects

I have a ModelForm which includes m2m field to images. User can upload images and crop them with my cool jquery cropper, then areas are saved as images and their IDs and thumbnail URLs are passed back to page and included as thumbnails with hidden inputs. I have no problem while form have no errors, and when it does, i can not just simply display thumbnails — all I have is IDs, and form has no objects to iterate cause instance was not saved, and as it was not save it has no id and as it has no id it can not have m2m relations. So i wrote templatetag which returns queryset based on ids. It works like that: <ul id="lot-images" class="thumb-uploaders"> {% if form.errors %} {% load load_form_objects %} {% load_form_objects lot_form.images as images %} {% for image in images %} {% if image %} <li> <input type="hidden" name="images" value="{{image.id}}"/> <div class="image"> <div class="mask"></div> <img src="{{ image.get_thumbnail_url }}" alt=""/> <a href="#" class="delete">Удалить</a> </div> </li> {% else %} <li><a class="upload-medium"></a></li> {% endif %} {% endfor %} {% else %} <li><a class="upload-medium"></a></li> <li><a class="upload-medium"></a></li> <li><a class="upload-medium"></a></li> <li><a class="upload-medium"></a></li> <li><a class="upload-medium"></a></li> {% endif %} </ul>

  • m2m
  • form
  • errors
Read More

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

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

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

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

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

3110 snippets posted so far.