Improving select fields in Django with django-ajax-selects

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


  • Download the django-ajax-selects package and install it (python install)
  • Get jquery-plugin-autocomplete
  • In 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 config classes. To a model config class (admin.ModelAdmin) in 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 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 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 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.


Django web framework tutorials, 19 September 2011

Comment article
Comment article RkBlog main page Search RSS Contact