Improving select fields in Django with django-ajax-selects

Check out the new site at https://rkblog.dev.

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

Installing

  • Download the django-ajax-selects package and install it (python setup.py install)
  • Get jquery-plugin-autocomplete
  • In settings.py add 'ajax_select' to INSTALLED_APPS
  • In templates you will have to add few static files:
    • jquery-*.js
    • jquery.autocomplete.js
    • jquery.autocomplete.css
    • ajax_select.js
    • iconic.css (opcjonalne)
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 = [
			'/site_media/jquery-1.5.min.js',
			'/site_media/jquery-autocomplete/jquery.autocomplete.pack.js',
			]
		css = {
			'all': [
			'/site_media/jquery-autocomplete/jquery.autocomplete.css',
			'/site_media/jquery-autocomplete/iconic.css']
			}
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).

Configuration

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_LOOKUP_CHANNELS = {
    '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.

RkBlog

Django web framework tutorials, 19 September 2011


Check out the new site at https://rkblog.dev.
Comment article
Comment article RkBlog main page Search RSS Contact