Login

All snippets

Snippet List

Use crypt instead of sha1 as password hash algorithm

This snippet uses signals to replace the `contrib.auth.models.User.set_password()` function with one that uses *crypt* instead of *sha1* to hash the password. *Crypt* is of course cryptographically inferior to *sha1*, but this may be useful for interoperability with legacy systems e.g. when sharing a user authentication database with unix, a MTA etc. For some reason the `User` class doesn't emit a `class_prepared` signal, which would otherwise be a better choice here. That's why I had to resort to patching each `User` instance separately. A clean way to deploy this snippet is to place it in the `models.py` of an otherwise empty app, and add the app in `settings.INSTALLED_APPS`. The order of `INSTALLED_APPS` doesn't matter since we're patching instances, not classes.

  • password
  • hash
  • crypt
Read More

UTC DateTime field

A DateTime field extension that automatically stores the timezone, and the computed UTC equivalent. This field needs the pytz library. The field adds two new fields to the model, with the same name of the UTCDateTimeField field, and a suffix. For an UTCDateTimeField named 'updated', the model will contain * an 'updated' field, which holds the local datetime * an 'updated_utc' field, which holds the corresponding UTC datetime * an 'updated_tz' field, which holds the field timezone name The timezone can vary between model instances, just set the 'xxx_tz' field to the desired timezone before saving. UTCDateTimeField supports a single optional keyword argument 'default_tz', in addition to the DateTimeField standard ones, to let the user choose a provider for a default timezone when no timezone has been set. Its value can be * None (or the argument missing), in which case the default settings.TIME_ZONE will be used * a callable, which will be called when the 'xxx_tz' field is emtpy, which should return a timezone name * a string, which will be used to access a model attribute or call a model method, which should return a timezone name If the timezone name points to a non-existent timezone, a warning will be issued and the default settings.TIME_ZONE value will be used. The field will also add three properties to the model, to access the pytz timezone instance, and the offset aware datetimes for local time and UTC. For the same 'updated' field instance we used above, the three properties added to the model will be: * updated_timezone * updated_offset_aware * updated_utc_offset_aware A brief example on how to use UTCDateTimeField: class UTCDateTimeTest(models.Model): """ >>> import datetime >>> d = datetime.datetime(2007, 8, 24, 16, 46, 34, 762627) # new instance, tz from model method >>> t = UTCDateTimeTest(updated=d) >>> t.save() >>> t.updated datetime.datetime(2007, 8, 24, 16, 46, 34, 762627) >>> t.updated_utc datetime.datetime(2007, 8, 24, 14, 46, 34, 762627) >>> t.updated_tz 'Europe/Rome' >>> t.updated_timezone <DstTzInfo 'Europe/Rome' CET+1:00:00 STD> >>> t.updated_offset_aware datetime.datetime(2007, 8, 24, 16, 46, 34, 762627, tzinfo=<DstTzInfo 'Europe/Rome' CEST+2:00:00 DST>) >>> t.updated_utc_offset_aware datetime.datetime(2007, 8, 24, 14, 46, 34, 762627, tzinfo=<UTC>) >>> """ updated = UTCDateTimeField(default_tz='get_tz') def get_tz(self): return 'Europe/Rome'

  • models
  • fields
  • datetime
  • timezone
  • field
  • utc
Read More

Using reverse() to do redirects

When I initially set up my blog, I put together the archives with URL patterns like so: * `/weblog/2007/` goes to `archive_year` * `/weblog/2007/08/` goes to `archive_month` * `/weblog/2007/08/24/` goes to `archive_day` * `/weblog/2007/08/24/some-slug` goes to `object_detail` The same patterns held for links, only the prefix was `/links/` instead of `/weblog/`. For a forthcoming redesign/rewrite, I'm switching to using abbreviated month names (e.g., "aug", "sep", "oct", etc.) in the URLs, which means I need to redirect from the old-style URLs to the new. This snippet is the solution I hit upon. Two things are notable here: 1. Each one of these views uses [reverse()](http://www.djangoproject.com/documentation/url_dispatch/#reverse), called with the appropriate arguments, to generate the URL to redirect to. This means URLs don't have to be hard-coded in. 2. Each view takes an argument -- `object_type` -- which is used to generate the view name to pass to `reverse`, meaning that only one set of redirect views had to be written to handle both entries and links. This is just one of many handy tricks `reverse` can do :)

  • urls
  • reverse
  • redirects
Read More

CompressedTextField

A CompressedTextField to transparently save data gzipped in the database and uncompress at retrieval. Full description at my blog: [arnebrodowski.de/...Field-for-Django.html](http://www.arnebrodowski.de/blog/435-Implementing-a-CompressedTextField-for-Django.html)

  • text
  • model
  • field
  • compressed
Read More

duplicate model object merging script

Use this function to merge model objects (i.e. Users, Organizations, Polls, Etc.) and migrate all of the related fields from the alias objects the primary object. Usage: from django.contrib.auth.models import User primary_user = User.objects.get(email='[email protected]') duplicate_user = User.objects.get(email='[email protected]') merge_model_objects(primary_user, duplicate_user)

  • django
  • fields
  • model
  • generic
  • related
  • merge
  • duplicates
  • genericforeignkey
Read More

typygmentdown

Based heavily on [snippet #119](/snippets/119/), this is an all-in-one function which applies Markdown and typogrify, and adds Pygments highlighting (selected from a class name or by having Pygments guess the language) to any `<code>` elements found in the text. It also adds some niceties for picking up useful arguments to Markdown and Pygments, and registers itself as a markup filter with the `template_utils` formatter. Requirements: * [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) * [Pygments](http://pygments.org/) * [python-markdown](http://www.freewisdom.org/projects/python-markdown/) * [template_utils](http://code.google.com/p/django-template-utils/) * [typogrify](http://code.google.com/p/typogrify/)

  • pygments
  • markup
  • markdown
  • typogrify
Read More

extras.py for management commands

! Note - no longer needed Save this script in the same directory as manage.py and run it through the command line. It picks up project Command class instances. Something that will hopefully be fixed in the Django SVN version soon. Heres an example of a command: #utils/management/commands/sqlallall.py from django.core.management import call_command from django.core.management.base import BaseCommand from django.db import models class Command(BaseCommand): help = "Returns sqlall for all installed apps." def handle(self, *args, **options): """ Returns sqlall for all installed apps. """ for app in models.get_apps(): call_command("sqlall", app.__name__.split(".")[-2])

  • management
  • commands
Read More

in_list filter

which you would use like this: The item is {% if item|in_list:list %} in list {% else %} not in list {% endif %}

  • template
  • filter
  • lists
  • tag
  • contains
  • in
Read More

paginator using url tag

Example for provided django-tagging url snippet: {% paginator 4 image_tag_paged tag=tag page %} links then equals {% url image_tag_paged tag=tag,page=n %}

  • tag
  • pagination
  • url
  • paginator
Read More

JSONField

This is a great way to pack extra data into a model object, where the structure is dynamic, and not relational. For instance, if you wanted to store a list of dictionaries. The data won't be classically searchable, but you can define pretty much any data construct you'd like, as long as it is JSON-serializable. It's especially useful in a JSON heavy application or one that deals with a lot of javascript. **Example** (models.py): from django.db import models from jsonfield import JSONField class Sequence(models.Model): name = models.CharField(maxlength=25) list = JSONField() **Example** (shell): fib = Sequence(name='Fibonacci') fib.list = [0, 1, 1, 2, 3, 5, 8] fib.save() fib = Sequence.objects.get(name='Fibonacci') fib.list.append(13) print fib.list [0, 1, 1, 2, 3, 5, 8, 13] fib.get_list_json() "[0, 1, 1, 2, 3, 5, 8, 13]" *Note:* You can only save JSON-serializable data. Also, dates will be converted to string-timestamps, because I don't really know what better to do with them. Finally, I'm not sure how to interact with forms yet, so that realm is a bit murky.

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

If modulo template tag

Usage: {% ifmodulo forloop.counter 4 0 %} <!-- do something --> {% else %} <!-- do something else --> {% endifmodulo %} or {% ifnotmodulo 5 3 %} <!-- do something --> {% else %} <!-- do something else --> {% endifmodulo %} When the third parameter does not exist, it is assumed you're checking for values different than 0.

  • template
  • tag
  • if
  • modulo
Read More

3110 snippets posted so far.