Login

3110 snippets

Snippet List

ifinlist template tag

I recently had to write a custom template tag which checks to see if a value exists in a list variable from within a Django template. This was my first ever attempt at writing a template tag so any feedback would be appreciated.

  • template-tag
  • if-in-list
  • if-value-in-list
Read More

iter_fetchmany

When executing custom sql, the temptation is to use fetchall or fetchone, since the API for fetchmany is a bit awkward. (fetchall makes all records resident in client memory at once; fetchone takes a network round-trip to the DB for each record.) This snippet, hoisted from django.db.models.sql.query.results_iter, presents a nice, simple iterator over multiple fetchmany calls which hits a sweet spot of minimizing memory and network usage.

  • sql
  • db
  • db-api
  • fetchmany
Read More

simple app using RestViews

Inspired by [Eric Florenzano's](http://www.eflorenzano.com/) post about [writing simple and very fast pure-WSGI applications](http://www.eflorenzano.com/blog/post/writing-blazing-fast-infinitely-scalable-pure-wsgi/). Using [RestView](http://www.djangosnippets.org/snippets/1071/) approach. More about it on [my blog](http://my.opera.com/kubiku/blog/2009/01/16/bare-wsgi-vs-python-frameworks-django-chapter)

  • rest
Read More

Dynamic growing model

This model is designed for my webshop. The Client-object is very 'stretch-able' by defining more fields to the client. These extra fields ares stored in the ClientConfig-object. Be sure to create a new Client-instance first and SAVE it! Without a client.id the ClientConfig won't work.

  • django
  • dynamic
  • model
  • example
  • client
Read More

Load Windows ICO files

PIL IcoImagePlugin is twelve year old and it can't handle recent Windows ICO files. Here is a function that handles all ICO versions and preserve transparency. Usage: # Load biggest icon from file image = load_icon('icon.ico') # Save third icon as PNG load_icon('icon.ico', 2).save('icon.png')

  • image
  • pil
  • ico
Read More
Author: dc
  • 2
  • 2

Severity codes in user messages

This is the code for a template tag. Put this code in your template to render your messages: {% for message in messages %} {% render_user_message message %} {% endfor %} When you're adding a message to the user's message set, follow these rules: If you want a message to appear as an error, append "0001" to the end of it. To appear as a notice, append "0002" to it. To appear as a happy message, appear "0000" to it. If no code is present, it will default to displaying as an error. This makes use of the classes "error", "notice", and "success", so you need to define these in your CSS. For help with custom template tags, see [the Django docs](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/)

  • user
  • message
Read More

Formalchemy hack for newforms-based form validation

Very simple proof-of-concept that uses the django.forms library (newforms) for validation, and formalchemy for saving the model instance using sqlalchemy. it can be used like this (pseudo-code): if form.is_valid(): form.save(session=Session, app_label='Contact') Feel free to improve the concept. Ideally, either use formalchemy or django.forms but not both like this example. ;-)

  • newforms
  • hack
  • formalchemy
  • notmm
  • sqlalchemy
Read More

Breadcrumbs filter

Filter for a list if breadcrumbs. All necessary code included but obviously only the breadcrumbs method that is needed with necessary changes for esc(). I use it as {% load breadcrumbs %} {{ request.path|breadcrumbs:"" }} enclosed in an unordered html list with id="breadcrumbs"

  • filter
  • breadcrumbs
Read More

keywords arguments parser for custom template tags

returns a list of (argname, value) tuples (NB: keeps ordering and is easily turned into a dict). Params: * tagname : the name of calling tag (for error messages) * bits : sequence of tokens to parse as kw args * args_spec : (optional) dict of argname=>validator for kwargs, cf below * restrict : if True, only argnames in args_specs will be accepted If restrict=False and args_spec is None (default), this will just try to parse a sequence of key=val strings. About args_spec validators : * A validator can be either a callable, a regular expression or None. * If it's a callable, the callable must take the value as argument and return a (possibly different) value, which will become the final value for the argument. Any exception raised by the validator will be considered a rejection. * If it's a regexp, the value will be matched against it. A failure will be considered as a rejection. * Using None as validator only makes sense with the restrict flag set to True. This is useful when the only validation is on the argument name being expected.

  • template
  • tag
  • custom
  • template_tags
Read More

decorator to synchronize method at class / module level

This decorator allows you to wrap class methods or module functions and synchronize access to them. It maintains a dict of locks with a key for each unique name of combined module name and method name. (Implementing class name is lost in decorator? Otherwise it would have class name too if available.) Effectively it functions as a class level method synchronizer, with the lock handling completely hidden from the wrapped function.

  • decorator
  • method
  • class
  • synchronize
Read More

Filter; Capitalise Sentences (capsentence)

Given a string, it first lowercases it, then uppercases the first letter of each sentence. Helpful when dealing with awfully formatted entirely UPPERCASE XML product data feeds.

  • capitalize
  • capitalise
  • sentence
  • sentences
  • capitalises
  • capitalizes
  • prettifies
  • sentance
Read More
Author: djm
  • 1
  • 0

JSONable model base

This is a basic stub for a model that you can use to easily add customizable JSON serialization to your models. Make your model inherit from JsonableModel, and then define the models/yourmodel.json template with whatever information from the model that you want to make available.

  • model
  • json
  • inherit
Read More

Unusable passwords for LDAP users

An example of how to modify the admin user creation form to assign an unusable password to externally authenticated users when they are created. This code is more intimate with the django.contrib.auth classes than I'd like, but it should be fairly straightforward to maintain should the relevant django.contrib.auth classes change.

  • admin
  • ldap
  • password
Read More

HTTP basic auth decorator

This is a somewhat simpler alternative to [http://www.djangosnippets.org/snippets/243/](http://www.djangosnippets.org/snippets/243/) that does not return a 401 response. It's meant to be used along with the login_required decorator as an alternative way to authenticate to REST-enabled views. Usage: @http_basic_auth @login_required def my_view(request): ... If an HTTP basic auth header is provided, the request will be authenticated before the login_required check happens. Otherwise, the normal redirect to login page occurs.

  • basic
  • authentication
  • decorator
  • auth
Read More

BeforeFilter Middleware

Expanded version of [snippet 715](http://www.djangosnippets.org/snippets/715/ "Django snippets: Simple View Middleware to allow a Prefilter") to be more flexible. Updates: * 2009-04-24: Multiple filters now work correctly * 2009-03-22: Fixed bug * 2009-02-03: Simplified process.

  • middleware
  • process_view
  • beforefilter
Read More