- The workflow for using django-selectable involves two main parts:
- Defining your lookups
- Defining your forms
Including jQuery & jQuery UI
The jQuery and jQuery UI libraries are not included in the distribution but must be included in your templates. See the example project for an example using these libraries from the Google CDN. Django-Selectable should work with jQuery >= 1.4.4 and jQuery UI >= 1.8
You must also include a jQuery UI theme stylesheet. In the example project we've included the "lightness" theme via the Google CDN.
Defining a Lookup
The lookup classes define the backend views. The most common case is defining a lookup which searchs models based on a particular field. Let's define a simple model:
In a lookups.py we will define our lookup:
This lookups extends selectable.base.ModelLookup and defines two things: one is the model on which we will be searching and the other is the field which we are searching. This syntax should look familiar as it is the same as the field lookup syntax for making queries in Django.
Below this definition we will register our lookup class.
You should only register your lookup once. Attempting to register the same lookup class more than once will lead to LookupAlreadyRegistered errors. A common problem related to the LookupAlreadyRegistered error is related to inconsistant import paths in your project. Prior to Django 1.4 the default manage.py allows for importing both with and without the project name (i.e. from myproject.myapp import lookups or from myapp import lookups). This leads to the lookup.py file being imported twice and the registration code executing twice. Thankfully this is no longer the default in Django 1.4. Keeping your import consistant to include the project name (when your app is included inside the project directory) will avoid these errors.
Now that we have a working lookup we will define a form which uses it:
This replaces the default widget for the CharField with the AutoCompleteWidget. This will allow the user to fill this field with values taken from the names of existing Fruit models.
And that's pretty much it. Keep on reading if you want to learn about the other types of fields and widgets that are available as well as defining more complicated lookups.