Login

All snippets

Snippet List

Default to current/all sites in admin (updated!)

This code sets the default sites for a sites ManyToMany property to `Site.objects.all()`, which makes sure you don't have to bother setting it for each item on a site. This could easily be changed to `Site.objects.get_current()` to use the current site as default.

  • admin
  • sites
  • default
  • site
  • current
  • all
Read More

Django model cron jobs

Inspired by [snippet 1126](http://www.djangosnippets.org/snippets/1126/), I thought I would post a module that stores crontab entries in a database, with a less powerful, but more end-user friendly API. ("twice a week starting on Sat 1 Dec 2007, 6:23am", instead of "23 6,18 * * *"). The crontab is synchronised when an entry is changed, and relevant environment variables, function name and arguments are provided. You might want to store this as an app called "scheduler" to match the imports. Enjoy!

  • cron-jobs
  • scheduled-events
Read More

Allow editing of the selected object of the filter_vertical/filter_horizontal widget with jquery

This patch allows to open a popup to edit the selected object of either the left or right select input of a filter_horizontal or filter_vertical field, when pressing the "Insert" key. Being a noob with general client-side issue, it's served as a patch that suits my needs. Maybe it's possible to do it cleaner by overloading the javascript methods, or get rid of the jquery dependency in order to integrate it into django trunk ... Any contribution is welcome! It's licensed under WTFPL license. Requires jquery.

  • admin
  • jquery
  • widget
  • filter_horizontal
  • filter_vertical
Read More

Gravatar support for Django comments

A templatetag to add [Gravatar](http://www.gravatar.com/) support for [Django comments](http://docs.djangoproject.com/en/dev/ref/contrib/comments/ "Django Comments"). Based on [this snippet](http://www.djangosnippets.org/snippets/772/) but works for everyone who comments even if they are not a registered user.

  • comments
  • gravatar
Read More

Get stories by category and some date range

Removed for now... Not sure where to share new Ellington snippets due to the gray-area of it being proprietary. It's an awesome package but it's hard to find any good help with Django 91 code. Good luck ellingtoners!

  • date
  • stories
  • category
Read More

direct to template from a subdir

I needed a way to quickly get a direction of html pages templated such that another person could drop new templates in to a subdirectory and without modifying urls.py or views.py get them up and being displayed. Now, the direct_to_template view provided django.views.generic.simple can sort of do this with a urlpattern like: `url(r'^(?P<template>.*\.html)$', direct_to_template)` But that means your templates, no matter what level in the url hierarchy they are reached at, have to be defined at the root of a template directory. I wanted them retrieved from a specific subdirectory instead so I could provide a little wall for them. Hence this snippet. To use you would have url pattern that looked like: `url(r'^foo/(?P<template>.*\.html)$', direct_to_template, {'subdir' : 'subdir/'}),` Which will template any url that matches <parent url>/foo/bar.html for any 'bar'. The problem is if this is a sub-url pattern match this is going to look for the template "bar.html" when we may actually want it to get the template "<parent url>/foo/bar.html"

  • templating
  • wildcard
  • subdir
Read More

Google Analytics Templatetag

This template tag allows easy inclusion of google analytics script. If Google changes the script in the future, it remains easy to update the template tag with the the new code. This script is tested against Django 1.0 trunk Oct 9 2008. **Readme** After signing up for a Google Analytics account for your domain, define ANALYTICS_ID = "UA-XXXXXXX-X" in your settings.py with the supplied code. Include {% load analytics %} at the top of your base.html and {% analytics %} tag at just before the closing 'body' tag of the base template. Make a template to hold the analytics script. templates/analytics/analytics_html

  • templatetag
  • google-analytics
  • django-1.0
Read More

Prefill ForeignKey caches

Provides an efficient means of looking up multiple related model instances for a range of objects by pre-filling the cache attribute used by `SingleRelatedObjectDescriptor` with either complete model instances or a dict containing only specified fields, looking up all required data with a single query. Example usage: C:\django_projects\soclone>django-admin.py shell >>> from soclone.models import Question >>> from soclone.views import populate_fk_caches >>> from django.db import connection >>> from django.contrib.auth.models import User >>> q = Question.objects.get(id=1) >>> a = list(q.answers.all()) >>> connection.queries = [] >>> populate_fk_caches(User, ( ... ((q,), ('author', 'last_edited_by', 'closed_by')), ... (a, ('author', 'last_edited_by')), ... ), ... fields=('username', 'gravatar', 'reputation', 'gold', 'silver', ... 'bronze')) >>> connection.queries [{'time': '0.000', 'sql': u'SELECT "auth_user"."id", "auth_user"."username", "au th_user"."gravatar", "auth_user"."reputation", "auth_user"."gold", "auth_user"." silver", "auth_user"."bronze" FROM "auth_user" WHERE "auth_user"."id" IN (1, 2)' }]

  • foreignkey
  • cache
  • prefill
Read More

Twisted protocol for receiving logging module messages over a socket

When using Python's logging module in a concurrent environment (e.g. mod_python), messages get dropped by the standard file-based handlers. The [SocketHandler](http://www.python.org/doc/2.5.2/lib/node414.html) allows you to send logging messages to a remote socket. This snippet provides code for listening for such messages and writing them out to a log file. The final log file is configured as a standard logging file-based handler.

  • logging
  • twisted
Read More

Convert numbers in USA notation to brazilian notation

**This is the converter, just put it as a filter and call it with a float number.** * So, if you have a template variable **{{ my_number }}** that is "3096.44". * It will convert to "3.096,44" using the filter **{{ my_number|numBR }}**.

  • convert
  • float
  • usa
  • br
  • brazil
Read More

update_or_create

Django provides a `get_or_create` helper method in the `models.Manager` class which looks up an object for the given `kwargs`, creating one if necessary. But sometime you need a method which updates the object with given `kwargs` or creates it if it's not found. This snippet provides the helper for that purpose. Use the snippet like this: from django.db import models class PersonManager(models.Manager): update_or_create = _update_or_create class Person(models.Model): first_name = models.CharField() last_name = models.CharField() city = models.CharField() objects = PersonManager() person, created, updated = Person.objects.update_or_create(first_name="John", last_name="Smith", defaults=dict(city="London")) The method returns a tuple of (`object`, `created`, `updated`), where `created` and `updated` are booleans specifying whether an `object` was created or updated respectively. Both `created` and `updated` are `false` if `object` is neither created nor updated (that is `object` has just been fetched "as is" from db). This happens if the update fails.

  • model
  • helper
  • update
  • create
Read More

Jinja2 integration + application specific functions/filters/tests

Jinja2 is an alternative template system that can be plugged into django. It offers greator flexibility in presentation logic; if you find the django template system too restrictive, you should have a look at Jinja2 (The syntax is very similar). In Jinja, you don't need costum tags (most of the time), because you can call functions and pass them parameters too! The only problem is that you cannot "load" functions from the template, this "loading" must be done by the code that renders the template. Same goes for filters and tests. If you need only two or three functions/filters, no problem, you can manually add them to the Environment object; but this method doesn't really scale with real-life webapps. This module/snippet offers a solution by allowing the user to define application-specific functions and filters and load them into the jinja2 environment automatically. Here's how to use this: 1. Install Jinja2 (for a quick & dirty installation, you can just put the jinja2 folder in a folder that's in PYTHONPATH) 2. Save this python module somewhere and call it something meaningful (I have it as jinja.py in my project directory) 3. Whenever you need to respond (an HttpResponse) with a template that's rendered by jinja, import this module and call `return jrespond( template_name, context )` 4. Any filters or functions you define in any of your applications will be readily available inside the template (see the documentation in code)

  • template
  • templates
  • jinja
  • template-tags
  • jinja2
Read More

3110 snippets posted so far.