Login

All snippets written in Python

Snippet List

RestfulView

In the same vein as [snippet 436](http://www.djangosnippets.org/snippets/436/), this allows you to differentiate view logic by HTTP method such as GET, POST, PUT, DELETE. This is also very useful combined with the [HttpMethodsMiddleware snippet](http://www.djangosnippets.org/snippets/174/). I am not the author, but I have found it to be very helpful.

  • rest
  • http
  • urlconf
Read More

View dispatch based on HTTP verb

Sometimes, when views are particularly complex, it's useful to send the different request methods to different functions. If you have to do this frequently, the repetition gets tiring. This helper class can be used to simplify that.

  • http
  • urlconf
Read More

Redirect Multiple Domains to a Single Domain

Often, you may register more than one domain name for your website, which may have a primary domain of *mysite.com.au*: 1. mysite.com 2. my-site.com 3. mysite.net 4. mysite.co.uk For SEO and brand awareness reasons, (remember: every page should have exactly one URL) you want every visitor to end up on your primary domain, *mysite.com.au*. This middleware checks the HTTP_HOST for all incoming requests, and sends the user to http://www.mysite.com.au/ if they've managed to hit another domain.

  • middleware
  • redirect
  • domains
Read More

Include captchas from recaptcha.net

Recaptcha is a free service that helps you protect your forms against spam bots by displaying a picture showing 2 words or playing an audio file telling 8 digits for the visually handicapped. After registration on http://recaptcha.net a private and a public key are generated. Put the keys in settings.py. Find client code for recaptcha at http://pypi.python.org/pypi/recaptcha-client. Put the file captcha.py into application root.

  • captcha
  • recaptcha
Read More
Author: b23
  • 8
  • 29

CSS Preprocessor

Here is a Django view that turns code like this: @variables { $varcolor: #333; } body { color: $varcolor; padding: 20px; } .space { padding: 10px; } .small { font-size: 10px; } #banana(.space, .small) { margin-bottom: 10px; } And turns it into something like this: body { color: #333; padding: 20px; } #banana { padding: 10px; font-size: 10px; margin-bottom: 10px; } .small { font-size: 10px; } .space { padding: 10px; } Notice the variables declaration at the top. The other feature is *extending* - here #banana extends .space and .small. The url.py entry might look something like this: (r'^css/(?P<css>(\w|-)+)\.css$','csspp.csspp'), Here referencing csspp.py in your path (root directory of your site probably). The code also looks for a CSS_DIR setting in your settings file. You will probably want to point straight to your media/css/ directory. **Known problems** * There is now way of extending selectors that are already extending something else. In the example code there is now way to extend #banana since it is already extending .small and .space.

  • css
  • preprocessor
  • csspp
Read More

Logging Middleware

This is a simple Logging Middleware that uses the python logging functions. Simply drop this snippet in a file in your project such as `logmw.py` (don't try to call it `logging.py` though), then add the class to MIDDLEWARE_CLASSES in your settings file. (for instance, `'mysite.logmw.LoggingMiddleware'`) Updated 8/25/08: added PhonyLogger class that swallows log messages when logging is disabled, so code doesn't have to care if it's on or not (thanks to goodness for suggesting the idea, though I missed it before)

  • middleware
  • logging
Read More

CleanCharField

I was about to start an online community but every time you allow people to post something as a comment you never know what they come up to, especially regarding profanities. So I come up with this idea, I put together some code from the old style form validators and the new newform style, plus some code to sanitize HTML from snippet number [169](http://www.djangosnippets.org/snippets/169/), and the final result is a CharField that only accept values without swear words, profanities, curses and bad html. Cheers.

  • validator
  • newforms
  • forms
  • html
  • sanitize
  • profanities
Read More
Author: DvD
  • -2
  • 0

AMF Message passing through Middleware

Middleware for communicating with Flash Player via Flashticle and Django. Setup a view at /gateway/math/multiply like so: def multiply(request, m1, m2): return m1 * m2 Then in your Flex/Flash app you call "math.multiply" on a NetConnection pointing to http://domain.com/gateway/ Does not yet support authentication.

  • flash
  • amf
  • flashticle
Read More

Functional Filters

I've been working on a project where I realized that I wanted to call methods on Python objects *with arguments* from within a Django template. As a silly example, let's say your application maintains users and "permissions" that have been granted to them. Say that permissions are open-ended, and new ones are getting defined on a regular basis. Your `User` class has a `check_permission(p)` method that return `True` if the user has been granted the permission `p`. You want to present all the users in a table, with one row per user. You want to each permission to be presented as a column in the table. A checkmark will appear in cells where a user has been granted a particular permission. Normally, in order to achieve this, you'd need to cons up some sort of list-of-dicts structure in Python and pass that as a context argument. Ugh! Here's how you'd use the `method`, `with`, and `call` filters to invoke the `check_permission` method from within your template. (Assume that you've provided `users` and `permissions` as context variables, with a list of user and permission objects, respectively.) <table> <tr> <th></th> {% for p in permissions %} <th>{{ p.name }}</th> {% endfor %} </tr> {% for u in users %} <tr> <td>{{ u.name }}</td> {% for p in permissions %} <td> {% if user|method:"check_permission"|with:p|call" %}X{% endif %} </td> {% endfor %} </tr> {% endfor %} </table> The `call_with` method is a shortcut for single-argument invocation; for example, we could have re-written the above as {% if user|method:"check_permission"|call_with:p %}...{% endif %} Anyway, this has been useful for me. Hope it's helpful for others! --chris P.S., tip o' the cap to Terry Weissman for helping me polish the rough edges!

  • filter
  • filters
  • function
  • object
  • method
Read More

Automatically trim newforms text fields

Makes sure the value a user entered into a a text-based field is automatically trimmed during form cleaning / validation. The 'field' parameter is expected to be a newforms.fields.Field _instance_.Only modifies str and unicode descending values, and passes everything else on untouched. Example: form = form_for_model(Person) make_trimming(form.fields['name'])

  • newforms
  • strings
  • trim
Read More

filter/search a newforms select widget

Adds a filter input above a select widget that allows live-filtering on the client-side (no ajax) in Firefox. Example: make_fields_searchable(ModelItemForm, { 'publisher': {'set_size': 8}, 'developer': {'set_size': 8}, 'genre': {}, 'platform': {} })

  • filter
  • newforms
  • search
  • model
  • widgets
  • select
Read More

Logging solution for mod_python/FCGI

The solution is based on [dballanc's snippet](http://www.djangosnippets.org/snippets/420/). Can easily be combined with any of the [SQL tracing solutions](http://www.djangosnippets.org/tags/debug/). You might want to run a separate logging server and redirect your logs there. Please refer to the [logging reference manual](http://docs.python.org/lib/module-logging.html).

  • log
  • mod_python
  • debug
  • logging
  • fcgi
Read More

Middleware for printing of exception to console

The django debug screens are great, but only when you can see them. Trying to debug javascript/ajax calls can be kind of a pain. This just a copy/paste of some code in django's internals stuck in a middleware so that exceptions also print to the dev server console.

  • middleware
  • console
  • exception
Read More

2956 snippets posted so far.