Login

Most bookmarked snippets

Snippet List

Improved many-page pagination

This one was adapted from [Page numbers with ... like in Digg](http://djangosnippets.org/snippets/1441/). See that one for more reference. Digg-like page numbering using inclusion tag. Usage in template: `{% load pagination %} {% pagination yourpage %}` Inclusion template pagination.html: {% if page.has_previous %} <a href="?page={{ page.previous_page_number }}"><img src="{{ MEDIA_URL }}images/page/cyclenav_l.png" alt="Previous page" /></a> {% endif %} {% for pnum in begin %} <a href="?page={{ pnum }}"{% if page.number == pnum %} class="active"{% endif %}>{{ pnum }}</a> {% endfor %} {% if middle %} <strong>...</strong> {% for pnum in middle %} <a href="?page={{ pnum }}"{% if page.number == pnum %} class="active"{% endif %}>{{ pnum }}</a> {% endfor %} {% endif %} {% if end %} <strong>...</strong> {% for pnum in end %} <a href="?page={{ pnum }}"{% if page.number == pnum %} class="active"{% endif %}>{{ pnum }}</a> {% endfor %} {% endif %} {% if page.has_next %} <a href="?page={{ page.next_page_number }}"><img src="{{ MEDIA_URL }}images/page/cyclenav_l.png" alt="Previous page" /></a> {% endif %}` Produces: previous_img 1 2 ... 4 5 6 7 8 9 10 11 12 ... 17 18 next_img Or: 1 2 3 4 5 6 7 8 ... 17 18 next_img Or: previous_img 1 2 ... 10 11 12 13 14 15 16 17 18 next_img

  • tag
  • django
  • templatetag
  • pagination
  • digg
  • pages
Read More

Multiple cache backend

Sometimes you might find useful to cache a value in different backends. Just put this code in a file named "multicache.py" somewhere in your python path and set it in CACHE_BACKEND setting: CACHE_BACKEND = 'multicache://?fallback=1&backends=file:///var/tmp/django_cache,locmem://' Separate the backends settings with commas, the first one will be set as default. Setting fallback to 1 provides fallback to default backend.

Read More

Django code generator

django-app-generator takes as an input your project (ORM) and generates repetitive code. At this moment there is only one example a simple RESTservice, but goal is to build alternative implementation of admin panel that will be fully customizable. The project is in the beta stage, if you encounter any problems feel free to create an issue.

  • Admin
  • REST
  • code-generator
Read More

ReportBug() (exception emails - ala django debug style)

ReportBug() allows you to send exception details to you, via email, but with far more detail than the default. It uses the base function for the traceback used by the Debug mode on Django. This is a first revision, so the emails have no decent styling, but it works, and shows scope on each stack. It will automatically generate a random serial number per error, so you can track them in your favourite bug tracker. It also has support for you to pass it a request variable, so the mail would also contain request/response context. Again, i'm gonna look into doing this manually in the future. Hope this helps! Mwah. Cal Leeming. cal [at] simplicitymedialtd.co.uk. Simplicity Media Ltd.

  • email
  • debug
  • mail
  • exception
  • report
  • bug
  • mail_admins
  • reportbug
Read More

Easy configuration for relocatable sites

Deploying relocatable Django sites isn't currently as trivial as it should be (see http://code.djangoproject.com/ticket/8906, http://groups.google.com/group/django-developers/tree/browse_frm/thread/fa3661888716f940/). This snippet relocates all url patterns (similarly to http://djangosnippets.org/snippets/2129/) as well as the absolute url settings of `settings.py`. This allows deployment under a different mount point with a single Django setting, without having to repeat the mount point again as a SCRIPT_NAME parameter supplied by the web server.

  • deployment
  • mount point
  • relocatable
Read More

Query lookups using operators

This class emulates query lookups to behave as numeric operators. Inspired by SQLAlchemy. User.objects.filter( X('username') == 'diverman' ) User.objects.filter( X('username') != 'diverman' ) User.objects.filter( X('pk') > 10 ) User.objects.filter( X('pk') >= 10 ) User.objects.filter( X('pk') < 10 ) User.objects.filter( X('pk') <= 10 ) User.objects.filter( X('username') % 'iverma' ) User.objects.filter( X('username') << 'diver' ) User.objects.filter( X('username') >> 'man' ) User.objects.filter( X('pk') | (1, 2, 3) )

  • q
  • query
  • lookup
  • operator
Read More

Update applications

This snippet is based on 928. I've added the support to update a custom folder, using shell arguments. It requires the argparse module. You can install it with: pip install argparse Usage: # Updates repositories in the specified <folder path> # The default is the ./ folder update_repos --path <folder path> # List available options update_repos -h Alessandro Molari

  • update
  • applications
  • svn
  • git
  • baazar
  • mercurial
  • repositories
Read More

View Redirect Decorators

Temporary and permanent view redirect decorators. Simplifies views that always redirect to a specific or configured url. You can use the reverse() function (or any other runtime-required lookup) via `lambda` to define the redirect url.

  • view
  • decorator
  • redirects
Read More

Continuing and breaking from loops in Django templates

This snippet makes Django templates support `break` and `continue` in loops. It is actually more powerful than the respective Python statements as it allows breaking and continuing from an outer loop, not just the innermost. `break` and `continue` are implemented as template filters, with the input value being the loop variable. For example, to break from the current `for` loop use `forloop|break`, and to continue from the next outer loop use `forloop.parentloop|continue`. The implementation monkeypatches Django (specifically Nodelist and ForNode) and has been tested on v1.2 with Python 2.6.

  • template
  • loop
  • break
  • continue
Read More

NoneWidget

Sometime may be useful to disable the HTML output from formfield to template.

  • widgets
  • widget
Read More

Python-like string interpolation in Javascript

Provides python-like string interpolation. It supports value interpolation either by keys of a dictionary or by index of an array. Examples: interpolate("Hello %s.", ["World"]) == "Hello World." interpolate("Hello %(name)s.", {name: "World"}) == "Hello World." interpolate("Hello %%.", {name: "World"}) == "Hello %." This version doesn't do any type checks and doesn't provide formating support.

  • template
  • javascript
  • string interpolation
  • replace
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

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

3110 snippets posted so far.