Login

All snippets written in Python

2956 snippets

Snippet List

Auto rendering decorator with options

This view decorator renders automaticaly the template with the context provided both by the view "return" statement. For example: @auto_render def my_view(request): ... return 'base.html', locals() You can still return HttpResponse and HttpResponseRedirect objects without any problems. If you use Ajax requests, this decorator is even more useful. Imagine this layout: def aggregating_view(request): ... context = locals() partial1 = partial_view_1(request, only_context=True) partial2 = partial_view_2(request, only_context=True) # aggregate template include partial templates return 'aggregate.htmt', context.update(partial1).update(partial2) def partial_view_1(request): ... return 'partial_1.html', locals() def partial_view_2(request): ... return 'partial_2.html', locals() This way you can render you view individualy for specific ajax calls and also get their context for the aggregating view.

  • render_to_response
  • ajax
  • decorator
  • rendering
Read More

Autoload Django Models When Using ./manage.py shell

It's a pain to import all the Django models you want to use in the Python shell every time you start it. Here's how you can get IPython to autoload all your Django models for you every time you start the shell using ./manage.py shell. Put the code in a .py file in the root of your project. Then tell IPython to load the script in ~/.ipython/ipythonrc in the "Python files to load and execute" section.

  • import
  • shell
  • interpreter
  • autoload
Read More

Template tag: Extend with parameters

Extended extends tag that supports passing parameters, which will be made available in the context of the extended template (and all the way up the hierarchy). It wraps around the orginal extends tag, to avoid code duplication, and to not miss out on possible future django enhancements. Note: The current implementation will override variables passed from your view, too, so be careful. Some of the argument parsing code is based on: http://www.djangosnippets.org/snippets/11/ Examples: {% xextends "some.html" %} {% xextends "some.html" with title="title1" %} {% xextends "some.html" with title="title2"|capfirst %}

  • template
  • templatetag
  • extends
  • parameters
Read More

Instance partial update

If you're like me, you've got a models with a lot of fields/foreignkeys and often only want to edit a portion of the model in a form. Add this method to your custom form class and use it in place of the save() method.

  • forms
  • model
  • partial
  • updating
Read More

Templatetag for JS merging and compression

**Javascript merging and compression templatetag** One of the most important things for improving web performance is to reduce the number of HTTP requests. This is a templatetag that merges several javascript files (compressing its code) into only one javascript. It checks if this merged file is up to date, comparing modification time with the other javascripts to merge. Usage: {% load jsmerge %} {% jsmerge mergedfile js/file1.js js/file2.js js/file3.js %} The previous code will: 1. Search in `settings.MEDIA_ROOT` for all files passed by parameter. 2. Create a `/path/to/media_root/mergedfile.js` (if it doesn't exist or it's not up to date). This file is a merging plus compression of all javascripts. 3. Return this HTML fragment: `<script type="text/javascript" src="/media_url/mergedfile.js"></script>`

  • javascript
  • merging
  • compression
  • tunning
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

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