Login

All snippets

Snippet List

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

local django test

Sometimes I would like to test a codesnippet without a complete django environment. Here is a small "local test script" you can use for this ;)

  • testing
  • test
  • local-test
Read More

Tablify templatetag

`{% tablify questions name response 8 %}` Will generate a table structure of a list, ensuring that a set number of columns is not exceeded. It takes 4 arguments: *Context Variable *Cell Header Attribute *Cell Data Attribute *Max Number of Columns The code will loop through the given variable, creating th and td elements for each item. It will create a new tr when the max number of columns is exceeded.

  • templatetag
  • table
Read More

Detect blog platform

Detect blog platform. As we all known, there are so many blog platform in the wild, e.g. Blogger.com, WordPress, LiveJournal, Movable Type etc. This little snippet could guess the blog platform according a url. Dependency: 1. pycurl 2. BeautifulSoup

  • detect
  • blog
  • type
  • platform
Read More

Last pages the user visited

This middleware remembers the last URLs that the user visited on your Django-site and saves them into the `request.session`. The fields are `currently_visiting` for the URL that is opened by the user and `last_visited` which is the URL before. Most of the time, you'll need only `last_visited`, as `currently_visiting` is just an implementation detail. For what is this good for? Imagine, you have to implement something like JavaScripts `history.back()` or `history.forward(-1)` but without JavaScript. Things start to get difficult when using JavaScript is not possible, for whatever reason. This snippet was created because I needed to redirect the user to the page he's been watching before clicking on the "translate" link. One other alternative would be adding the URL the user was visiting as a GET field to the "translate" link, but I hoped to find a possibility to avoid GET. This snippet works quite well as a proof of concept, the only known wart is when the user uses tabs or multible windows on the site, things get messed up. This cannot be solved, it's a restriction imposed by the design of HTTP.

  • middleware
  • session
  • user
Read More

Forcing unit test runner to abort after failed test

Sometimes running a test suite can take a long time. This can get especially annoying when you see a failure or error, but have to wait for all the remaining tests to run before you can see the relevant stack traces. Pressing ctrl+c to interrupt the tests does not work; the KeyboardInterrupt exception does not get caught and only a stack trace irrelevant to your tests is produced. This behavior can be altered through overriding the testcase's `run` method and catching the exception yourself. Now you can stop the tests whenever you want to and still see what is wrong with your tests.

  • unit-test
Read More

Ordered items in the database

First off: This snippet is more or less obsoleted by [snippet #259](/snippets/259/). The way that snippet #259 uses feels cleaner and more usable. It is basically the same code but the magic works a little bit different. In case you prefer this way, I've left this snippet as-is. Maybe you know this problem: you have some objects in your database and would like to display them in some way. The problem: the Django ORM does not provide any way to sort model instances by a user-defined criterion. There was already a plug-in in SQLAlchemy called [orderinglist](http://www.sqlalchemy.org/docs/plugins.html#plugins_orderinglist), so implementing this in Django was basically not a big deal. Usage is (due to use of meta-classes) quite simple. It is recommended to save this snippet into a separate file called `positional.py`. To use it, you only have to import `PositionalSortMixIn` from the `positional` module and inherit from it in your own, custom model (but *before* you inherit from `models.Model`, the order counts).

  • db
  • orm
  • database
  • plugin
  • mixin
Read More

Getting the global error of a form

You may want to access to "global" errors in your template, typically when you have a custom `clean()` method which checks several fields. `{{ form.errors }}` gives an < ul >, which is often not what you want, and `{{ form.errors|join:", " }}` iterates in the keys of `errors` (which are the names of fields, uninteresting). The global `errors`'s key is "__all__", and Django doesn't allow us to do `{{ form.errors.__all__ }}`. This method returns an array, like a classic `{{ form.field.errors }}`, and can be used with a join : `{{ form.get_global_errors|join:", " }}`.

  • newforms
  • forms
Read More

view by view basic authentication decorator

A simple decorator that requires a user to be logged in. If they are not logged in the request is examined for a 'authorization' header. If the header is present it is tested for basic authentication and the user is logged in with the provided credentials. If the header is not present a http 401 is sent back to the requestor to provide credentials. The purpose of this is that in several django projects I have needed several specific views that need to support basic authentication, yet the web site as a whole used django's provided authentication. The uses for this are for urls that are access programmatically such as by rss feed readers, yet the view requires a user to be logged in. Many rss readers support supplying the authentication credentials via http basic auth (and they do NOT support a redirect to a form where they post a username/password.) Use is simple: ` @logged_in_or_basicauth def your_view: ... ` You can provide the name of the realm to ask for authentication within.

  • basic
  • authentication
  • decorator
Read More

custom sql without table names

Keeps database table names out of custom SQL code, but still allows for correct parameter passing in the execute function. (psycopg doesn't substitute table or field names, only data, in the execute function)

  • sql
  • postgres
Read More

SSL Middleware for Webfaction

*NOTE Stephen updated his original snippet http://www.djangosnippets.org/snippets/85/ to work with WebFaction, please use his version now* This code is 95% from Stephen Zabel's snippet at http://www.djangosnippets.org/snippets/85/. However, his snippet, as it was, wouldn't work when enabling SSL for the admin site on Webfaction. For some reason, the default request.is_secure() doesn't behave properly with Webfaction's setup and redirects. One thing Webfaction does do is add X-Forwarded-ssl='on' to any https requests. So instead of using request.is_secure(), I've just used that. To setup the admin site with SSL on Webfaction, do the following: 1. Install this middleware wherever you like, and add it to settings.py 2. In your Webfaction panel, create your 'django' application ("application" in the Webfaction sense, not the Django sense) 3. Create two sites. The first, your main site (which I'll call example.com), should use the application 'django' mounted at '/'. Do *not* have HTTPS enabled on this site. 4. For the second site, also use the application 'django', and again mount it to '/', but this time enable HTTPS. 5. In your urls.py, modify the admin URL as follows: `(r'^admin/', include('django.contrib.admin.urls'), {'SSL':True} )` That should be it! The admin section of the site now requires SSL (as specified in urls.py), and if anyone tries to access the admin via regular http, a redirect to https will occur.

  • ssl
  • webfaction
Read More

Admin list thumbnail

This code will add a thumbnail image to your Model's Admin list view. The code will also generate the thumb images, so the first view may be a little slow loading. This assumes you have an **ImageField** in your Model called **image**, and the field's **upload_to** directory has a subdirectory called **tiny**. You then must add **"thumb"** to your Model's Admin **list_display**. The thumbnail images are also linked to the full size view of the image. I found this **VERY** useful... hope someone else does as well.

  • admin
  • imagefield
Read More

3110 snippets posted so far.