Login

Top-rated snippets

Snippet List

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

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

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

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

Complex Formsets

Background ========== Edit: This snippet doesn't make a lot of sense when Malcolm's blog is down. Read on for some history, or go [here](http://www.djangosnippets.org/snippets/1955/) to see the new trick that Malcolm taught me. A year ago, Malcolm Tredinnick put up an excellent post about doing complex Django forms [here](http://www.pointy-stick.com/blog/2008/01/06/django-tip-complex-forms/). I ended up reinventing that wheel, and then some, in an attempt to create a complex formset. I'm posting my (partial) solution here, in hopes that it will be useful to others. Edit: I should have known - just as soon as I post this, Malcolm comes back with a solution to the same problem, and with slightly cleaner code. Check out his complex formset post [here](http://www.pointy-stick.com/blog/2009/01/23/advanced-formset-usage-django/). I'll use Malcolm's example code, with as few changes as possible to use a formset. The models and form don't change, and the template is almost identical. Problem ======= In order to build a formset comprised of dynamic forms, you must build the forms outside the formset, add them, and then update the management form. If any data (say from request.POST) is then passed to the form, it will try to create forms inside the formset, breaking the dynamically created form. Code ==== To use this code: * Copy `BaseDynamicFormSet` into your forms.py * Create a derived class specific to your needs (`BaseQuizDynamicFormSet` in this example). * Override `__init__`, and keep a reference to your object that you need to build your custom formset (`quiz`, in this case). * Call the parent `__init__` * Call your custom add forms logic * Call the parent `_defered_init` To write your custom add_forms logic, remember these things: * You've got to pass any bound data to your forms, and you can find it in self.data. * You've got to construct your own unique prefixes by doing an enumerate, as shown in the example above. This is the same way it is usually handled by the formset. Add a `formset_factory` call, and specify your derived dynamic formset as the base formset - we now have a `QuizFormSet` class that can instantiated in our view. The view and template code look identical to a typical formset, and all of the dynamic code is encapsulated in your custom class. Warning ======= This solution does not yet handle forms that work with files, use the ordering/delete features, or adding additional forms to the set via javascript. I don't think that any of these would be that hard, but don't assume that they'll just work out of the box.

  • formset
Read More

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

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

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

Email Munger

Template filter to hide an email address away from any sort of email harvester type web scrapers and so keep away from spam etc. The filter should be applied on a string which represents an email address. You can optionally give the filter a parameter which will represent the name of the resulting email href link. If no extra parameter is given the email address will be used as the href text. {{ email|mungify:"contact me" }} or {{ email|mungify }} The output is javascript which will write out the email href link in a way so as to not actually show the email address in the source code as plain text. Also posted on [my site](http://www.tomcoote.co.uk/DjangoEmailMunger.aspx).

  • filter
  • email
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

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

Play nice with ModelAdmin mixins

There are several nice ModelAdmin subclasses that provide useful functionality (such as django-batchadmin, django-reversion, and others), but unfortunately a ModelAdmin can really only subclass one at a time, making them mutually exclusive. This snippet aims to make mixing these classes in as easy as possible -- you can inherit your model admin from it, add a tuple of mixins, and it will dynamically change the inheritance tree to match. This isn't guaranteed to work with all ModelAdmins, but so long as the mixins play nice with django modeladmin they *should* work.

  • mixin
  • modeladmin
Read More

Media Wiki With mwlib

### Simple wiki with MediaWiki and Markdown Support Once you install the mwlib you can use mwit to convert Mediawiki markup to HTML. I am include the model that uses it to hopefully provide a good example. I maintain a version and only one copy of each wiki entry in the main table and archive replaced markup into another table, you will need to create the archive model or remove that section of code. The line ending changes in mwit are so that it will work with IE.

  • markup
  • markdown
  • mediawiki
  • wiki
  • archive
Read More

Image resize on demand

** Image on demand view ** I often post photos on photography fora. Most fora want you to place a link to a photo somewhere on the net, but different fora have different rules. Some fora want you to stick to a maximum of 800 pixels wide, some 700 pixel and some even strange values like 639 pixels. My own site uses 600 pixels so I end up resizing images all the time. Since I keep my originals with my gallery as well (hidden for public viewing) resizing on the fly would be a nice asset. I'm using my previous snippet to apply a slight unsharp mask for better web display of my photos. ** usage ** This snippet takes the url to my photo application which is a simple link using the pk of my photo table and adds 'width'.jpg to the end (some fora check if the link is an image based on extenstion) The view takes the width requested and creates the resized image from the original full size image or takes it from the cache for display on demand. To prevent a dozen directories I use a setting to specify which widths are allowed, providing room for several versions of the same image. Any improvements are appreciated since I'm still rather inexperienced in Python and Django.

  • image
  • pil
  • resize
  • pythonmagick
Read More

3110 snippets posted so far.