Login

Top-rated snippets

Snippet List

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

Load templatetag libraries via settings

In your settings file: TEMPLATE_TAGS = ( "djutils.templatetags.sqldebug", ) Make sure load_templatetags() gets called somewhere, for example in your apps __init__.py *Edit: Updated to work with templatetag libraries that use certain critical django-bits.*

  • templates
  • settings
  • tags
  • templatetags
  • conf
Read More

nofollow filter

This filter add extra attribute **rel="nofollow"** to any "<a ..." element in the value, which does not contain it already. I use this to filter comments text in my blog.

  • filter
Read More

Flickr Sync

This code provides a Django model for photos based on Flickr, as well as a script to perform a one-way sync between Flickr and a Django installation. *Please note that the snipped contains code for two files, update.py and a Django model.* *The two chunks are separated by:* """ END OF FLICKRUPDATE """ """ START DJANGO PHOTO MODEL Requires django-tagging (http://code.google.com/p/django-tagging/) """ My model implements tagging in the form of the wonderful django-tagging app by Jonathan Buchanan, so be sure to install it before trying to use my model. The flickrupdate.py code uses a modified version of flickerlib.py (http://code.google.com/p/flickrlib/). Flickr returns invalid XML occasionally, which Python won't stand for. I got around this by wrapping the return XML in `<flickr_root>` tags. To modify flickrlib to work with my code, simply change the this line: return self.parseData(getattr(self._serverProxy, '.'.join(n))(kwargs)) to: return self.parseData('<flickr_root>' + getattr(self._serverProxy, '.'.join(n))(kwargs) + '</flickr_root>') I hate this workaround, but I can't control what Flickr returns. flickrupdate will hadle the addition and deletion of photos, sets and tags. It will also keep track of photos' pools, although, right now, it doesn't delete unused pools. This is mostly because I don't care about unused pools hanging around. It's a simple enough addition, so I'll probably add it when I have a need. Be sure to set the appropriate information on these lines: api_key = "YOUR API KEY" api_secret = "YOUR FLICKR SECRET" flickr_uid = 'YOUR FLICKR USER ID' I hadn't seen a Django model and syncing script, so I threw these together. I hope they will be useful to those wanting start syncing their photos.

  • flickr
  • photos
  • photo
  • flicker
Read More

browscap.ini-parser

Sometimes you need to know if a visitor is a bot or if the browser supports certain features or if it is a mobile device. The easiest way to do so would be to lookup the user agent in a capabilities database. Fortunately there is already such a database called browscap.ini which is widely known among PHP users. I found the file accidently on my harddrive because it is also used by Mono: /etc/mono/browscap.ini Read http://browsers.garykeith.com/index.asp for more information. Before importing the module you need to call the script from commandline to retrieve the browscap.ini file. Look at the test function to see how to use it. You can also create a file called "bupdate.ini" which can contain fixes for wrong or incomplete entries, e.g: [Konqueror] javaapplets=True

  • ie
  • browscap
  • browser
  • detection
  • firefox
  • opera
  • mozilla
  • safari
Read More

TerminalLoggingMiddleware

A handy ANSI-colored logging mechanism to display the SQL queries and times in the terminal when using django-admin.py runserver. DEBUG mode must be true for this to work.

  • sql
  • middleware
  • terminal
  • logging
Read More

Newforms Autocomplete Widget with Scriptaculous

From [here](http://gacha.id.lv/blog/26/01/2007/django-autocompletefield/) with litle improvements. [More about Script.aculo.us and Django](http://wiki.script.aculo.us/scriptaculous/show/IntegrationWithDjango)

  • ajax
  • newforms
  • autocomplete
Read More

template + cache = crazy delicious

A couple of utility `Node` subclasses that will automatically cache thier contents. Use `CachedNode` for template tags that output content into the template: class SomeNode(CachedNode): def get_cache_key(self, context): return "some-cache-key" def get_content(self, context): return expensive_operation() Use `CachedContextUpdatingNode` for tags that update the context: class AnotherNode(CachedContextUpdatingNode): # Only cache for 60 seconds cache_timeout = 60 def get_cache_key(self, context); return "some-other-cache-key" def get_content(self, context): return {"key" : expensive_operation()}

  • tag
  • templatetag
  • cache
Read More

Timedelta template tag

This is tag similar to *timesince* and *timeuntil*, which work great until you starting giving timesince dates in the future or timeuntil dates in the past. Timedelta tag will humanize output correctly for both future and past dates using *now* as a default reference date (or a specified reference date as argument) now = Apr 27 2007 futuredate = May 5 2007 pastdate = Jan 5 2007 {{ futuredate|timedelta }} will output "in 1 week, 1 day" {{ pastdate|timedelta }} will output "3 months, 2 weeks ago"

  • template
  • date
  • time
  • humanize
Read More

jsonify template filter

Simple template filter to encode a variable to JSON format Usage: {% load json_filters %} {% block content %} &lt;script type="text/javascript"&gt;<![CDATA[ var items = {{ items|jsonify }}; ]]>&lt;/script&gt; {% endblock %} I'm using JsonResponse for the views but I also want to have preloaded JSON data into the page output

  • template
  • filter
  • json
Read More

HttpMethodsMiddleware

This middleware allows developers to "fake" browser support for HTTP methods. Even though most modern browsers only support GET and POST, the HTTP standard defines others. In the context of REST, PUT and DELETE are used for client interaction with the server. For forms with a PUT or DELETE method, this middleware will change them to go through POST, and will include an invisible field called "method_middleware_transform" that carries the originally intended method. So, `<form method="PUT" ...>...</form>` More or less becomes `<form method="POST" ...><input type=hidden name="method_middleware_transform" value="PUT"></form>` (with a few other minor HTML modifications) The process is completely transparent to the developer... you never have to deal with the fact that browsers don't support the standard methods. **One caveat** is that server interaction via `XMLHttpRequest` (AJAX) requires special attention... this middleware won't properly setup your XMLHttpRequest to take advantage of this functionality. This is a combination of the work of Jesse Lovelace and the Django CSRF middleware.

  • middleware
  • rest
Read More

Filter on Multiple M2M Objects Simultaneously

This snippet should allow you to do queries not before possible using Django's ORM. It allows you to "Split" up the m2m object you are filtering on. This is best described by example: Suppose you have `Article` and `Tag`, where `Article` has a m2m relation with `Tag` (`related_name = 'tag'`). If I run: from django.db.models.query import Q Article.objects.filter(Q(tag__value = 'A') & Q(tag__value = 'B')) > # no results I would expect to get no results (there are no tags with both a value of 'A' and 'B'). However, I *would* like to somehow get a list of articles with tags meeting that criteria. Using this snippet, you can: from django.db.models.query import Q from path.to.qsplit import QSplit Article.objects.filter(QSplit(Q(tag__value = 'A')) & QSplit(Q(tag__value = 'B'))) > # articles with both tags So now they are split into different `Tag` entries. Notice how the `QSplit()` constructor takes a `Q` object---it's possible to give this any complicated Q-type expression.

  • models
  • q
  • m2m
  • db
  • orm
Read More

Generate a CSV file for a model

This code generates a CSV file for a model. The URL is http://example.com/spreadsheets/app_label/model_name/ (replace spreadsheets for admin, from the URL for the model's admin page.)

  • csv
Read More

3110 snippets posted so far.