Login

All snippets

Snippet List

Email Attachment

Django documentation is lacking in giving an example for sending an email with attachment. Hopefully this code helps those who are trying to send email with attachments

  • email
  • attachment
  • fileinput
Read More
Author: sri
  • 2
  • 12

Frequently used tags/filters for Jinja2

Some frequently used filters and global functions: **url** - same as django url tag **nbspize** - replace all spaces with nbsp **get_lang** - get current language code **timesince** - converted django timesince tag **timeuntil** - converted django timeuntil tag **truncate** - tag that truncates text call it with an str argument like '20c' or '5w', where the number provides the count and c stands for charachters and w stands for words

  • tags
  • jinja
  • jinja2
Read More

Jinja2 Django integration

Integration of django and Jinja2. Just import render_to_response from this file and you are ready. This file automatically adds template search path from yout TEMPLATE_DIRS and from each installed application. You can also use several variables in your settings.py to add filters, tests and global functions to the default context. This can be done by using JINJA_GLOBALS, JINJA_FILTERS and JINJA_TEST e.g. `JINJA_FILTERS = ( 'myapp.filters.myfilter', 'myapp.filters.myfilter2', )`

  • templates
  • jinja
  • jinja2
Read More

Timedelta Database Field

This subclass of django.models.Field stores a python datetime.timedelta object as an integer column in the database. It includes a TimedeltaFormField for editing it through djangos admin interface. Feedback welcome. 2011-04-20: TimedeltaField can now be (de)serialized. Tested with JSON. 2009-11-23: `_has_changed()` added. Before form.changed_data contained timedelta FormFields, even if nothing changed.

  • datetime
  • timedelta
  • dbfield
Read More

Making prepopulate_from work with ForeignKeys and other sorts of choice fields

This is a fairly small bit template that, if placed in your_project_dir/templates/admin/prepopulated_fields_js.html will override the template that is normally pulled by the preopulated fields templatetag in the admin. The result is that you can successfully specify a ForeignKey or other field involving choices as a source for prepopulate_from in your admin.py. It works just as well when there are multiple fields of both the text and choice variety.

  • javascript
  • admin
  • prepopulate
Read More

CheckedField

Here's a snippet to pair an arbitrary form Field type (the "target field") with a checkbox. If the checkbox is not selected, the cleaned_data value for the field will be None. If the checkbox is selected, it will return the target field's cleaned value.

  • checkbox
  • forms
  • combining
Read More

DRY custom ModelAdmin.list_display methods with a decorator

If you add a lot of custom `ModelAdmin` methods to `list_display` like I do, you know it can require a lot of repetition. Notice how adding 'checkbox' to `list_display` requires typing the method name 4 times: class ExampleAdmin(admin.ModelAdmin): list_display = ['checkbox', '__str__'] def checkbox(self, object): return '<input type="checkbox" value="%s"/>' % object.pk checkbox.short_description = mark_safe('&#x2713;') checkbox.allow_tags = True Using this decorator, the name only needs to be typed once: class ExampleAdmin(admin.ModelAdmin): list_display = ['__str__'] @add(list_display, mark_safe('&#x2713;'), 0, allow_tags=True) def checkbox(self, object): return '<input type="checkbox" value="%s"/>' % object.pk

  • admin
  • modeladmin
  • list_display
Read More

whitespaceoptimize block tag

This is a custom block tag and is used like this: {% load whitespaceoptimize %} {% whitespaceoptimize "css" %} /* CSS comment */ body { color: #CCCCCC; } {% endwhitespaceoptimize %} And when rendered you get this output: body{color:#CCC} To install it, download the snippet and call it `myapp/templatetags/whitespaceoptimize.py`. (Make sure you have a `__init__.py` in the `templatetags` directory) You need to download and install [slimmer](http://www.issuetrackerproduct.com/Download#slimmer) and put on your Python path. The block tag can be used for `javascript` and `html` as well as `css`. You can also let it guess the format; this would work for example: {% whitespaceoptimize %} <table> <tr> ... {% endwhitespaceoptimize %} ...but this would just replicate the functonality of the [built-in spaceless tag](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#spaceless)

  • tag
  • block
  • whitespace
  • slimmer
Read More

Orderable inlines using drag and drop with jQuery UI

An easy way of making inlines orderable using drag-and-drop, using [jQuery UI's](http://ui.jquery.com/) sortable() plugin. First, add an "order" field to the inline models which is an IntegerField, and set that model to use 'order' as its default order_by. Then hook in the JavaScript. This should make them drag-and-drop sortable using jQuery UI, and also hide the divs containing those order fields once the page has loaded. This technique is unobtrusive: if JavaScript is disabled, the order fields will be visible and the user will be able to manually set the order by entering numbers themselves.

  • jquery
  • inlines
  • pyconuk2008
Read More

keeping Model and Field History (everywhere)

Usage: class MyModel(ModelWithHistory): class History: model = True # save model changes into admin's LogEntry table fields = ('f1', 'f2') # save these fields history to AttributeLogEntry table f1 = CharField(max_length=100) f2 = IntegerField() for threadlocals, see http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser Aware! Not thoroughly tested yet. May cause problems with loading fixtures.

  • model
  • history
Read More

Alphabetic filter for admin

This snippet is based on [#748](http://www.djangosnippets.org/snippets/748/). Adds filtering by first char (alphabetic style) of values in the admin filter sidebar. The example below results in this filter: By name that starts with All A B G M X urls.py example (only for register the filter): import <your project>.admin.filterspecs models.py example: from django.db import models class Person(models.Model): name = models.CharField(max_length=40) name.alphabetic_filter = True admin.py example: class Admin: list_filter = ['name']

  • filter
  • admin
  • filterspec
Read More

FreeBSD rc.d FastCGI Script

This is a simple rc script, suitable for starting a FastCGI daemon on FreeBSD. Simply copy this into /usr/local/etc/rc.d , change all references to "signet" to the name of your app, mark it executable and modify /etc/rc.conf accordingly.

  • fcgi
  • freebsd
  • fastcgi
  • rc.d
  • rc
Read More

Retrieve a list of countries from GeoNames

GeoNames provides a useful data file with information about every country in the world (DjangoPeople uses this). Here's an importer that grabs the file from the web and turns it in to a list of dictionaries.

  • countries
  • geonames
Read More

3110 snippets posted so far.