Login

All snippets

Snippet List

Execute a signal once

Decorates signals for executing only one time Exemple usage : from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.contrib.auth.models import User @one def user_welcome(sender, instance, created, **kwargs): # Send a welcome email if created == True and isinstance(instance, User): instance.message_set.create(message=_(u"Ho, Welcome %s!" % instance)) subject, from_email, to = 'Welcome !', '[email protected]', instance.email text_content = render_to_string('mail/welcome.html', { 'user': instance }) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.send()

  • decorator
  • signals
  • once
Read More

Dynamic tabular inlines with optional drag-n-drop sorting

This jQuery javascript enables dynamic add/delete of rows in tabular inlines. It adds a "+" icon at the bottom of the inline to allow addition of new rows, and replaces the default delete checkbox with a "x" icon for deletion, giving you the possibility to add/delete rows instantly without reloading the page. In addition, it gives you drag-n-drop ordering functionality with a named position model field using jQuery UI Sortable. **Usage (see below for example):** Just include the javascript on your admin page, together with jQuery, and it'll automatically affect all tabular inlines. Optionally, also include jQuery UI Sortable and an Integer field in your inline model named "position" (or whatever you set "position_field" to), which will automatically hide the position field and enable drag-n-drop sorting. **Developed for:** * jQuery 1.3.2 * jQuery UI 1.7.1 * Django trunk (tested in Django v1.0.2) * (Might work with other versions with or without adjustments, but not tested) **Settings (in top of javascript):** * "position_field" is the name of an integer model field that is used for ordering the inline model. If left empty or not found, the drag-n-drop functionality is dropped. Defaults to "position". * "add_link_html" for custom look of "add"-buttons. Defaults to Django's built-in "+" image icon. * "delete_link_html" for custom look of "delete"-buttons. Defaults to Django's built-in "x" image icon. **Use example: ** *admin.py:* class NameInline(admin.TabularInline): model = Name extra = 1 class PersonAdmin(admin.ModelAdmin): inlines = [NameInline] class Media: js = ['js/jquery-1.3.2.min.js', 'js/ui/ui.core.js', 'js/ui/ui.sortable.js', 'js/dynamic_inlines_with_sort.js',] css = { 'all' : ['css/dynamic_inlines_with_sort.css'], } admin.site.register(Person, PersonAdmin) *models.py:* class Person(models.Model): year_born = models.PositiveIntegerField(_('year born'), null=True, blank=True) class Name(models.Model): profile = models.ForeignKey(Profile, verbose_name=_('profile')) position = models.PositiveIntegerField(_('position'), default=0) name = models.CharField(_('name'), max_length=100) class Meta: ordering = ('position',) *dynamic_inlines_with_sort.css:* /* To make row height of saved items same as others */ .inline-group .tabular tr.has_original td { padding-top:0.5em; } .inline-group .tabular tr.has_original td.original p { display:none; } Please post bugs in comments.

  • javascript
  • dynamic
  • admin
  • sort
  • jquery
  • ordering
  • inlines
  • inline
  • tabular
  • sortable
Read More

jQuery slugify plugin

This plugin lets you make a field(ideally for a slug) populate itself based on the value of another field. You use it like this: jQuery('#id_title').slugify('#id_slug');

  • slug
  • jquery
  • slugify
Read More

Django Breadcrumbs Snippet

A simple tag to render breadcrumbs. Usage: {% load breadcrumbs %} {% breadcrumbs "['Home','Home','home']" "['Articles','Articles','articles']" "['object','object','object.get_absolute_url']" %} Loads up the template in "modules/breadcrumbs.html" and renders it with a list of items. You can provide the tag either with plain text stuff and named urls as the third argument ( any more arguments per bracket-block is parsed as args / kwargs for the reverse() call ) or the object directly, and the script tries after failing the reverse() to resolve the provided arguments. Have pun.

  • django
  • templatetag
  • breadcrumbs
Read More

Python Calendar wrapper template tag

This tag gives you an iterable Python [Calendar object](http://docs.python.org/library/calendar.html) in your template namespace. It is used in the [django-calendar](http://github.com/dokterbob/django-agenda) project. Use it as follows in your template: {% get_calendar for <month_number_or_variable> <year_or_variable> as calendar %} <table> <tr> <th>Mon</th> <th>Tue</th> <th>Wed</th> <th>Thu</th> <th>Fri</th> <th>Sat</th> <th>Sun</th> </tr> {% for week in calendar %} <tr> {% for day in week %} <td>{{ day.day }}</td> {% endfor %} </tr> {% endfor %} </table>

  • template
  • tag
  • date
  • calendar
Read More

Pretty print SQL of query sets

Install [sqlparse](http://code.google.com/p/python-sqlparse/) with `easy_install sqlparse` and then you can easily debug the SQL like this: def view(request): data = MyModel.objects.filter(something__very=complex) print_sql(data) ... Inspired by [Simon Willison](http://simonwillison.net/2009/Apr/28/)

  • sql
  • queryset
  • sqlparse
Read More

CrashKit Middleware

Catch exceptions and send it along with useful data to [CrashKit](http://crashkitapp.appspot.com/).

  • middleware
  • exception
  • crashkit
Read More
Author: wiz
  • 1
  • 2

testdata tag for templates

The "testdata" tag allows you to inline test data into your templates, similar in spirit to Python doctests. There are two sections--the test data and the actual template to be rendered. In non-test mode your template renders normally from whatever views call it, and there is very little overhead to skip over the test data section (happens at parse time). Here are the goals: 1. Provide convenient way to test templates without surrounding infrastructure. 2. Make templates be self-documenting in terms of expected data. 3. Allow insertion of test data at arbitrary places in template structure. Hello-world looks like this: {% load handytags %} {% testdata %} { 'greeting': 'Hello', 'planet': 'World', } {% --- %} {# This is where the actual template begins #} {{ greeting }} <b>{{ planet }}</b> {% endtestdata %} To invoke it, set up urls.py with something like this: url(r'^testdata/(?P<template_path>.*)', test_template) def test_template(request, template_path): context = {'testdata_use': True} # put request vars into context to help choose # which test data we want to render for field in request.GET: context[field] = request.GET[field] return render_with_request(template_path, context, request) Then call: http://127.0.0.1:8000/testdata/hello_world.html Features: 1. The testdata tag's rendering will expose missing variables a bit more aggressively than Django normally does. 2. You have the full power of the template language to set the test data (which ultimately gets eval'ed as a Python expression). 3. As mentioned above, the tag is mostly unobtrusive. Limitations/caveats: 1. Right now the only data format I support is pure Python, but the tag could be modified pretty easily to support JSON or YAML. 2. The VerboseContext class is pretty heavy-handed--I really just want a hook into Django to tell it to render a section with more strictness about variables. Suggestions welcome. 3. You can put the testdata tag pretty much anywhere, but the normal rules apply...for example, if you are in a template that has the extend tag, you'll want to put the testdata tag in individual blocks.

  • templates
  • testing
  • doctest
  • custom-template-tag
Read More

Default to a static template.

Default to a static template. **Example:** urlpatterns = patterns('', ... # this rule SHOULD BE the last one (r'^(?P<template>[a-z-_/]+/?)?$', 'myproj.apps.myapp.views.static_template'), )

  • template
  • static
  • default
Read More

Content Moderator

This snippet is for [django-flag](http://code.google.com/p/django-flag/) Pinax app to make it generic moderator for any content model. You don't need to modify neither your model nor your views to moderate your flagged content objects.

  • generic
  • pinax
Read More

JSONField

This is a custom field that lets you easily store JSON data in one of your model fields. This is updated to work with Django 1.1. **Example: (models.py)** from django.db import models import JSONField class MyModel(models.Model): info = JSONField() ** Example: (shell)** >>> obj = MyModel.objects.all()[0] >>> type(obj.info) <type 'NoneType'> >>> obj.info = {"test": [1, 2, 3]} >>> obj.save() **[Code at GitHub](http://github.com/bradjasper/django-jsonfield/tree/master)**

  • models
  • fields
  • model
  • json
  • db
  • field
  • json-field
  • jsonfield
Read More

Truncate HTML without breaking tags

Put it in appname/templatetags/truncatehtml.py and load it with {% load truncatehtml %}, then for instance {{ some_story|truncatehtml:100 }} to truncate the story to 100 characters. Tags are not counted in the length given, and character entities count as one character. The filter should never break an open-tag text close-tag sequence without adding in the close tag. It will also preserve character entities. It won't sanitize the HTML, though: garbage in, garbage out. There's a bit more info about how it works in a [blog post](http://ole-laursen.blogspot.com/2009/05/safe-truncation-of-html.html) I wrote.

  • template
  • filter
  • truncate
  • html
Read More

3109 snippets posted so far.