Login

All snippets

Snippet List

Sharpening images

Returns a sharpened copy of an image. Resizing down or thumbnailing your images with PIL.Image tends to make them blurry. I apply this snippet to such images in order to regain some sharpness.

  • image
  • pil
  • sharpen
  • thumbnail
Read More

Multilingual Models

A way to implement models with translatable content. The translatable field of the default language has no extension, like "title" and the translations have extensions postfixes "_<two-letter language code>", like "title_la" or "title_mn". Method get_title() in this case returns the translation of the currently chosen language or the title of the default language, if the translation is not set. The class XFieldList overrides the default list class and is used for modifying ordering and list_display settings according the chosen language. For example, when the German language is chosen, the list of translatable content objects will be ordered by German titles (not English). *At the time when the list of field names is assigned to ordering or list_display (at the import of the model), the currently chosen language is still not known. But the language is known when ordering and list_display lists are used in contributed administration or elsewhere.* The XFieldList returns the modified values of the passed-in list, when its methods/properties are triggered. XFieldList transforms field names ending "_" (except the ones beginning with "__", like "__str__") to appropriate translations according the currently chosen language. For example ['title_', 'content_', 'is_published'] will be changed to ['title', 'content', 'is_published'] for the English language and to ['title_lt', 'content_lt', 'is_published'] for the Lithuanian language. *The best practice is to put XFieldList into a separate file and import it from different apps whenever needed.* It's worth mentioning that one implementing this should also know about [Django internationalization](http://www.djangoproject.com/documentation/i18n/).

  • i18n
  • l10n
  • translations
  • multilingual
Read More

ForeignKey dropdown selector

Most of the time when you want a dropdown selector based on a ForeignKey, you'll want to use [snippet #26](http://www.djangosnippets.org/snippets/26/) Here's an alternative approach, perhaps useful when you want to define choices once and reuse it in different views without overriding Form `__init__`.

  • dynamic
  • foreignkey
  • dropdown
  • choices
  • property
Read More

Dynamically specify TEMPLATE_DIRS

In your site’s settings.py module (in your site root), TEMPLATE_DIRS takes absolute paths. Here is a way to dynamically determine the absolute path to the application directory so you only have to specify relative paths within settings.py. Obviously, replace “application_directory” with the name of your application’s directory.

  • configuration
Read More

Lorem Ipsum - Random content for your mockups

The loremipsum tag generates random content for use in mockups. It takes this content from Cicero's De finibus bonorum et malorum. By default you get a random number of paragraphs up to 6, but you can affect this behaviour by passing in parameters for quantity and units. Units can be "paragraphs" or "words"; the default is paragraphs. Quantity dictates the number of units returned. If your django.conf.settings.TEMPLATE_DEBUG is True, then no output is returned, so you should be OK in the event you leave the tag in a production template. Syntax: {% loremipsum %} {% loremipsum quantity="3" units="paragraphs" %} By leaving the behaviour as random, you can see how your layout handles varying amounts of content. Handy, especially for multi-column pages. [Here's a stoopid site](http://lakes.knoxzilla.com/) where I'm playing with random text, pictures, business listings, etc. I do plan to add a "corpus" parameter to allow you to put your own corpus between lorumipsum and endloremipsum tags and a template parameter to specify the corpus should come from a template, but this has suited me well thus far.

  • tag
  • lorem
  • ipsum
  • mockup
Read More

Find all links in a value and display them separatley

This is a simple filter I use to display a list of links from a blog entry off in the sidebar ([example](http://www2.jeffcroft.com/blog/2007/feb/25/two-new-django-sites-both-source-available/)). Requires beautifulsoup. Originally by [Nathan Borror](http://playgroundblues.com), tweaked slightly by me.

  • template
  • filter
  • beautifulsoup
Read More

Using the {% widthratio %} template tag with CSS to create a bar graph

The {% widthratio %} template tag is under appreciated! Here, it's combined with CSS to create a bar graphic for the results of an election (this example comes from [this page](http://flickr.com/photos/postneo/405239750/in/photostream/), but has been modified slightly for simplicity's sake). The widthratio tag can be used to create all sorts of graphs and charts, as well as things like tag clouds. Here, we pass it the number of votes for a candidate, the total number of votes in the election, and the integer 190, which is the width, in pixels, of a "full" bar on the bar graph. In other words, 100% = 190 pixels. It works great!

  • template
  • templatetag
  • widthratio
  • graph
  • infographic
Read More

Using the built-in slugify filter outside a template

This is just a very short (and mostly useless on it's own) example of how the built in slugify filter can be used in a Python script to generate slugs. It was pulled from a script I've written to pull in items from Upcoming.org's API. I post it because "sunturi" posted [Snippet #29](http://www.djangosnippets.org/snippets/29/), which duplicates the functionality of the built-in slugify filter. In the comments of that snippet, santuri (and others) seem to believe that template filters can only be used within templates. This is incorrect, and I think it's important people understand they can be used elsewhere. sunturi's snippet does remove prepositions from values before slugifying them, so if you need that, his code will work work. But if all you need is slugification, the built-in slugify filter will work fine -- in a Python script, as well as in a template.

  • template
  • filter
  • django
  • slug
  • built-in
Read More

Another pygments for ReST

This is like [snippet 36](/snippets/36/). And it'll return css also. And it's not a filter.If the code parameter is skip, it'll test the code first, and if there is not a suiable lexer for the code, then use default python lexer to render the code. The code lanauage parameter is comes from pygments lexer alias. How to use it ---------------- html = to_html(rest_text) And there is a level parameter in to_html function, default is `2`, it's the sections level. And the html will be `css style + body` How to write ReST --------------------- Below is a example. This is a test. .. code:: def code(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): opt = {'display':'on'} opt.update(options) docnodes.Node(content, ''.join(arguments), **opt) if opt['display'].lower() == 'on': return [nodes.literal_block('', '\n'.join(content))] else: return [] .. code:: html+django <h1 id="title">通讯录</h1> <hr> <div> <table border="0" width="500"> <tr align="right"> <td>{% if has_previous %} <a href="/address?page={{ previous }}">上一页</a> {% endif %} {% if has_next %} <a href="/address?page={{ next }}">下一页</a> {% endif %}</td></tr> </table>

  • pygments
  • rest
Read More

Parsing and Highlighting &lt;code&gt; Blocks

This function takes a string (most likely from a template), searches it for `<code>[...]</code>`, highlights it with Pygments, and returns the entire thing back, as a string. (Note: the `<code>[...]</code>` must have a class corresponding to the language inside. If it lacks the class, then it's silently ignored.)

  • pygments
  • beautifulsoup
Read More

getattr template filter

Put inside `mysite/templatetags/getattr.py` Add `mysite` to your `INSTALLED_APPS` In your template: {% load getattr %} {{ myobject|getattr:"theattr,default value" }} Thanks to pterk for optimizations! \\o/

  • template
  • filter
  • get
Read More

3109 snippets posted so far.