Login

3110 snippets

Snippet List

Autoreload Apache on project modifications

This script will reload apache when any modifications are detected in a folder - useful only if the development server or mod_python's reload does not suit your needs for testing. It requires Linux 2.6.13+, Python 2.5, and the [development version of pyinotify](http://seb.dbzteam.com/pages/pyinotify-dev.html).

  • apache
  • reload
  • autoreload
  • modified
  • linux
  • pyinotify
Read More

html helpers for images and links

link and img are both HTML construction helpers. Good idea to use these helpers if your html don't fit into templates.

  • template
  • image
  • html
  • img-src
  • link
  • a-href
  • construction
  • helper
Read More

Per-site vary cache on language

I like the per-site caching offered by Django (it's simple) and I like the cache to be dependent on the chosen language. Unfortunately with the current `CacheMiddleware` you can either have the one or the other but not both at the same time. `VaryOnLangCacheMiddleware` is a small wrapper around `CacheMiddleware`. It looks at the `request.LANGUAGE_CODE` (set by `LocaleMiddleware`) and appends it to your `CACHE_MIDDLEWARE_KEY_PREFIX`. So "mysiteprefix" becomes "mysiteprefix_en" or "mysiteprefix_de-AT" depending on the user's chosen language. Site-wide, so no messing with per-view decorators and stuff. To use this, make sure `VaryOnLangCacheMiddleware` comes below `LocaleMiddleware` in your settings.py. If you haven't set your `CACHE_MIDDLEWARE_KEY_PREFIX`, it's works, too. **Update:** Replaced `super()` calls with `CacheMiddleware.xxx(self, ...)`.

  • middleware
  • i18n
  • cache
  • language
Read More

TruncateChars

**Usuage:** {{ comment.comment|truncatechars:20 }} **Why to use:** First of all, my english isn´t the best. I hope you will understand my text anyways :) Ok, I had a problem with some "kiddies" posting huge comments like "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaahhhhhhhhhhhhhhhhhhh this game rooooooooooocks!!!!!!!!!!!!!!!!". Django has no function to "kill" that huge words within a string. So I´ve coded this little peace and hope that someone could use it. Greets from Germany, Aveal http://www.onlinewars.eu

  • truncate
  • chars
Read More

xmlrpc basic auth

decorator which performs basic http auth authentication against the known userbase. This decorator is only for xml-rpc services. When there is no basic auth a proper response will be returned

  • auth
  • xmlrpc
Read More

Auto Logout Middleware

This Middleware is to log users out after a certain amount of time has passed. You'll want to add AUTO_LOGOUT_DELAY to your settings.py, set to a number of minutes after which a user should be logged out. It adds the key 'last_touch' to the session, you'll want to change that if you happen to be using that already.

  • middleware
  • auth
  • logout
Read More

PyCrust Shell

I thought it would be a neat idea to use the PyCrust shell for interacting with my models, instead of using the plain old shell. So what I did, is take a copy of the file: django/core/management/commands/shell.py Altered it, and saved it as: django/core/management/commands/pycrust.py For this to work, you should have pycrust installed (python-wxtools in ubuntu) and save this snippet as django/core/management/commands/pycrust.py, then run as follows: ./manage.py pycrust instead of ./manage.py shell Have fun!

  • pycrust
  • shell
Read More

Partial JSON template rendering

this decorator will render template and encode it as JSON string if it find **ajax_request** variable in GET. It will not parse parent (extended) templates, only given template and nested (included). Only blocks will be rendered and encoded to JSON naming block__*BLOCKNAME*. Simple javascript can do ajax request adding *?ajax_request* or *&ajax_request* (if needed) and update given html elements if they id's are same as block__*BLOCKNAME*. you can find a full code (including javascript) at my (http://projects.barbuza.info/trac/browser/django_addons/django_ajax/trunk/ sandbox).

  • ajax
Read More

Handling choices the right way

This solves the problem with **choices** described [here](http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/) Define your choices like this (in models.py): statuses = MyChoices(BIDDING_STARTED=10, BIDDING_ENDED=20) And then: status = models.IntegerField( default=statuses.BIDDING_STARTED, choices=statuses.get_choices() )

  • models
  • admin
  • choices
Read More

ingore_fields

I use this snippet when creating newforms with form_for_model and form_for_instance. Both do not have an argument that lets you filter out fields easily so I wrote this instead. Typical use: `form_class = form_for_instance(obj, fields=ignore_fields(model_class, ['field_name1']))`

  • newforms
  • fields
  • ignore
Read More

Copy/Paste form generation

Generator to help make newforms classes a bit like inspectdb does for generating rough model code. This is a standalone script to go in your project directory with settings.py and called from the prompt. It looks up the model, and generates code to copy/paste into your app. Hopefully to make a building a custom form with a lot of fields a little easier. Every argument should be a model identifier of form appname.modelname. Usage from the command line: python form_gen myapp.MyModel myapp.MyOtherModel

  • form
  • copy
  • generator
  • paste
Read More

Mako support as decorator

This snippet allows you to use @mako("templatename.mako") to define a mako template to use. Your python method just has to return a dictionary that will be passed to mako's context, after the addition of the "request" variable to the dictionary. If you return a non-False non dictionary object, it will return that instead of trying to render the template. The **request** variable is automatically added to the template's context. It also searches the current application's mako_templates/ subdirectory first before searching under the current directories mako_templates/, and does not use other application's mako_templates/ subdirectories at all. On Mako exceptions, it will display the Mako error page when debugging is enabled (hoping for extensible exception handling in the future to keep consistency) I got the idea from a [CherryPy tool](http://tools.cherrypy.org/wiki/Mako).

  • mako
Read More
Author: rmt
  • 2
  • 2

Sessions and authentication without cookies

[The Session documentation](http://www.djangoproject.com/documentation/sessions/) rightly warns of the dangers of putting a session ID into a query string. Sometimes, however, you have to do it - perhaps your client has mandated support for browsers with cookies disabled, or perhaps (as in my case) you're just dealing with a slightly broken client browser. This middleware pulls a session ID out of the query string an inserts it into the cookies collection. You'll need to include it in your MIDDLEWARE_CLASSES tuple in settings.py, *before* the SessionMiddleware. *Please* read my [full blog post](http://www.stereoplex.com/two-voices/cookieless-django-sessions-and-authentication-without-cookies) about for the dangers of doing this, and for full instructions and examples.

  • middleware
  • cookie
  • session
  • authentication
  • string
  • query
  • cookieless
  • querystring
Read More

Manager for something like __inall

Provides the method from_related_ids, which lets you select some objects by providing a list of related ids (The huge difference to __in is that the objects have to match al of the ids, not only one) Model Example:: class Article(models.Model): text = models.TextField() tags = ManyToManyField('Tag') objects = AllInManager() Usage:: Article.objects.from_related_ids((1,2,3,4), 'tags')

  • model
  • db
  • manager
Read More