Login

All snippets written in Python

Snippet List

run "silent" dev server

This will hide the scrolling output from the development server so you can ssh and run the server in peace, for those of us with only one SSH session active developing on a remote server.

  • bash
  • runserver
  • daemon
Read More

Left Outer join Q object

QLeftOuterJoin object allows you to create 'LEFT OUTER JOIN' sql query. It is very usefull if you have to define ForeignKey to 'null=True' (select_related will not work with null=True). You are allowed to use QLeftOuterJoin like Q object. Example: `QLeftOuterJoin('thread_last_post', Post, 'pk', Thread, 'last_post')` It will generates SQL like: LEFT OUTER JOIN appname_post AS thread_last_post ON thread_last_post.id = appname_thread.last_post_id Table could be model or string.

  • sql
  • q
  • query
  • join
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

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

2956 snippets posted so far.