Login

Most bookmarked snippets

Snippet List

Create nice looking PDFs from developer documentation

You need htmldoc, rst2html, the Python Imaging Libraray, BeautfiulSoup and spoon. The Debian/Ubuntu-packages are called htmldoc, python-docutils, python-imaging and python-beautifulsoup You can get spoon.py http://beautifulspoon.googlecode.com/svn/trunk/spoon.py To create the pdf files you have to call the script from django_src/docs Here is an example output: http://henning.cco-ev.de/django/essential.pdf

  • pdf
  • documentation
  • docs
Read More

Cache Manager

I had a problem: too many fetches from the DB. So, how to reduce load on the database without major changes to the code? Cache Manager is the answer. I've managed to reduce number of DB hits as much as 80% in some cases (dictionaries, complex relations). It is using standard cache mechanisms. I'm using it with mathopd. This is a very simple solution, instead of standard Manager, put this in your model definition as: `objects = CacheManager()` Then everythere elase in the code instead of all() or get(...) call all_cached() or get_cached(). I've kept original methods intact, to have an dual access, when you really, really must have frest data from the DB, and you can't wait for cache to expire. This is much easier to work with, then manually getting fetched data from the cache.No change to your existing code 9except model) and voila! Additionally if you have some data, you would like to store with your serialized object (e.g. related data, dynamic dictionaries), you can do this in the model method '_init_instance_cache'). Drop me an email if you find this useful. :)

  • cache
  • model
  • manager
Read More

UPDATED: Django Image Thumbnail Filter

A Django image thumbnail filter, adapted from code by [Batiste Bieler](http://batiste.dosimple.ch/blog/2007-05-13-1/). This updated version drops support for cropping and just rescales. You should use it in your templates like this: `<img src='{{ MEDIA_URL }}{{ image.get_image_filename|thumbnail:"300w,listingimages" }}' alt="{{ image.title }}" title="{{ image.title }}" />` This will produce a 300-pixel wide thumbnail of image, with the height scaled appropriately to keep the same image aspect ratio. 'listingimages' is the path under your MEDIA_ROOT that the image lives in - it'll be whatever upload_to is set to in your ImageField. If instead you wanted an image scaled to a maximum height of 140px, you'd use something like this: `<img src='{{ MEDIA_URL }}{{ image.get_image_filename|thumbnail:"140h,listingimages" }}' alt="{{ image.title }}" title="{{ image.title }}" />` Note the number has changed from 300 to 140, and the trailing letter from 'w' to 'h'. Please leave feedback and bug reports on [my blog, Stereoplex](http://www.stereoplex.com/two-voices/a-django-image-thumbnail-filter). I've only lightly tested this so you'll probably find something!

  • filter
  • image
  • thumbnail
Read More

Enhanced "avoid widows" template filters

Building on [jcroft's snippet](http://www.djangosnippets.org/snippets/17/), here's a slightly more advanced version which has two filters, one for basic text and the other for html snippets. Usage is like so: <h2>{{ blog_entry.headline|escape|widont }}</h2> {{ blog_entry.html|widont_html }} On top of Jeff's reasons for using these filters, they are important because they help keep one of [God's commandments](http://www.ebible.com/bible/NIV/Exodus+22%3A22). ;)

  • filter
  • widows
  • typography
  • widont
Read More

instant 'master' admin site

The newforms-admin branch (to be merged by 0.97, I think) is very nice to work with, separating models from the admin. It is trivial to create an admin site that includes every app that is installed. Note that you also get all your docs for things like template tags, etc.

  • admin
  • newforms-admin
Read More

keeptags: strip all HTML tags from output except a specified list of elements

Django has several filters designed to sanitize HTML output, but they're either too broad (striptags, escape) or too narrow (removetags) to use when you want to allow a specified set of HTML tags in your output. Thus keeptags was born. Some of the code is essentially ripped from the Django removetags function. It's not perfect--for example, it doesn't touch attributes inside elements at all--but otherwise it works well.

  • filter
  • html
  • escape
Read More

Fuzzy Time of Day

This filter will display the time as word(s) indicating roughly the time of day ("Morning", "Afternoon", "Evening", etc). For example, the following template snippet: Posted in the {{ post.date|fuzzy_time }} of {{ post.date|date:"F j, Y"} }}. will result in the following (assuming `post.date == datetime.datetime(2007, 6, 13, 20, 57, 55, 765000)`): Posted in the evening of June 13, 2007. The terms used and breakpoints (hours only) can be rather arbitrary so you may want to adjust them to your liking. See the docs for [bisect][] for help in understanding the code. Just remember you should have one less breakpoint than periods and the first breakpoint falls at the end of the first period. The idea was inspired by [Dunstan Orchard][1], although the code is *very* different (php case statement). He uses quite a bit more periods in a day, so you might want to take a look. [bisect]: http://docs.python.org/lib/module-bisect.html [1]: http://www.1976design.com/blog/archive/2004/07/23/redesign-time-presentation/

  • template
  • filter
  • time
Read More

HTTP headers view decorator

Decorator adding arbitrary HTTP headers to the response. This decorator adds HTTP headers specified in the argument (map), to the HTTPResponse returned by the function being decorated. Example: @headers({'Refresh': '10', 'X-Bender': 'Bite my shiny, metal ass!'}) def index(request): ....

  • http
  • view
  • decorator
  • headers
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

Auth decorators with 403

These decorators are based on user_passes_test and permission_required, but when a user is logged in and fails the test, it will render a 403 error instead of redirecting to login - only anonymous users will be asked to login.

  • auth
  • user_passes_test
  • 403
  • permission_required
Read More

RequestStack middleware

This is some very simple middleware that keeps track of the last 3 succesful requests for each visitor. This can be useful if you want to redirect the visitor to a previous path without relying on a hidden field in a form, or if you simply want to check if a visitor has recently visited a certain path. Note that this relies on the session framework and visitors actually accepting cookies. This can be easily modified to hold more requests if you have a need for it.

  • middleware
Read More

Referer-checking view decorators

Here are a couple of Django decorators for limiting access to a view based on the request's `HTTP_REFERER`. Both raise a Django `PermissionDenied` exception if the referer test fails (or a referer simply isn't provided). The first, `referer_matches_hostname`, takes a hostname (and port, if specified) and matches it against the referer's. If multiple arguments are supplied a match against any of the hostnames will be considered valid. The second, `referer_matches_re`, takes a regex pattern (like Django's urlpattern) and tests if it matches the referer. This is obviously more flexible than `referer_matches_hostname` providing the ability to match not just the hostname, but any part of the referer url. Finally there's an simple example decorator, `local_referer_only`, that limits a view to the current site by using Django's `django.contrib.sites` to look up the current hostname.

  • view
  • referer
  • decorator
  • http_referer
  • request
Read More

"If in" templatetag

It's been a while, but I think I made this by copying and pasting the default {% if %} tag and modifying it. Does what it says, lets you test for inclusion in a list, in templates, like so: {% ifin item list %}.

  • template
  • lists
  • tag
  • contains
Read More

3110 snippets posted so far.