Hardware, programming and astronomy tutorials and reviews.

Improving select fields in Django with django-ajax-selects

Replacing select lists with autocompleated ajax autocomplete widget

django-ajax-selects is a handy Django application that allows substituting select fields with ajax autocompleate fields. That can be done for example for Django admin panel and ForeignKey, ManyToMany fields. It solves the problems with select fields containing a lot of values.

django-ajax-selects in action


To add static files to add/edit admin panel pages we may use the admin.py config classes. To a model config class (admin.ModelAdmin) in admin.py you may add a "Media" subclass:
	class Media:
		js = [
		css = {
			'all': [
Those paths must point to existing files. The ajax_select.js can be found in "js" folder in django-ajax-selects. Either copy it to your site_media or add it to the static imports (if you are using the new in Django 1.3 static system). When you will be testing the application in action check dev server output - if all static files were found (no 404 responses).


To use django-ajax-selects we need to configure one or more rules for searching records. All rules are stored in AJAX_LOOKUP_CHANNELS in the settings.py file, like so:
    'ajax_related_articles' : dict(model='pages.article',search_field='title'),

"ajax_related_articles" rule will look for record in the "article" model from "pages" application using "title" field values.

Next step is to hookup that rule to the form in admin panel. In admin.py in the model config class add something like this:
form = make_ajax_form(Article, dict(related_articles='ajax_related_articles',))
Where "Article" is the model name. As second arg for make_ajax_form you pass a dictionary where keys are model field names (for which this widget will be used) and values are the rule names defined in settings.py. In this example "related_articles" select field will be replaced with the ajax based widget.

Django-ajax-selects has more features - like applying that widget to other forms, or custom search rules. All those features are described on the project page.


19 September 2011;

Comment article