Registry API

class autocomplete_light.registry.AutocompleteRegistry(autocomplete_model_base=None)[source]

AutocompleteRegistry is a dict of AutocompleteName: AutocompleteClass with some shortcuts to handle a registry of autocompletes.

autocomplete_model_base

The default model autocomplete class to use when registering a Model without Autocomplete class. Default is AutocompleteModelBase. You can override it just before calling autodiscover() in urls.py as such:

import autocomplete_light
autocomplete_light.registry.autocomplete_model_base =                 autocomplete_light.AutocompleteModelTemplate
autocomplete_light.autodiscover()

You can pass a custom base autocomplete which will be set to autocomplete_model_base when instanciating an AutocompleteRegistry.

autocomplete_for_generic()[source]

Return the default generic autocomplete.

autocomplete_for_model(model)[source]

Return the default autocomplete class for a given model or None.

classmethod extract_args(*args)[source]

Takes any arguments like a model and an autocomplete, or just one of those, in any order, and return a model and autocomplete.

register(*args, **kwargs)[source]

Register an autocomplete.

Two unordered arguments are accepted, at least one should be passed:

  • a model if not a generic autocomplete,
  • an autocomplete class if necessary, else one will be generated.

‘name’ is also an acceptable keyword argument, that can be used to override the default autocomplete name which is the class name by default, which could cause name conflicts in some rare cases.

In addition, keyword arguments will be set as class attributes.

For thread safety reasons, a copy of the autocomplete class is stored in the registry.

unregister(name)[source]

Unregister a autocomplete given a name.

autocomplete_light.registry.register(*args, **kwargs)[source]

Proxy method AutocompleteRegistry.register() of the registry module level instance.

autocomplete_light.registry.autodiscover()[source]

Check all apps in INSTALLED_APPS for stuff related to autocomplete_light.

For each app, autodiscover imports app.autocomplete_light_registry if possing, resulting in execution of register() statements in that module, filling up registry.

Consider a standard app called cities_light with such a structure:

cities_light/
    __init__.py
    models.py
    urls.py
    views.py
    autocomplete_light_registry.py

Where autocomplete_light_registry.py contains something like:

from models import City, Country
import autocomplete_light
autocomplete_light.register(City)
autocomplete_light.register(Country)

When autodiscover() imports cities_light.autocomplete_light_registry, both CityAutocomplete and CountryAutocomplete will be registered. See AutocompleteRegistry.register() for details on how these autocomplete classes are generated.

Autocomplete class API

AutocompleteInterface

class autocomplete_light.autocomplete.base.AutocompleteInterface(request=None, values=None)[source]

An autocomplete proposes “choices”. A choice has a “value”. When the user selects a “choice”, then it is converted to a “value”.

AutocompleteInterface is the minimum to implement in a custom Autocomplete class usable by the widget and the view. It has two attributes:

values

A list of values which validate_values() and choices_for_values() should use.

request

A request object which autocomplete_html() should use.

It is recommended that you inherit from AutocompleteBase instead when making your own classes because it has taken some design decisions favorising a DRY implementation of AutocompleteInterface.

Instanciate an Autocomplete with a given request and values arguments. values will be casted to list if necessary and both will be assigned to instance attributes request and values respectively.

autocomplete_html()[source]

Return the HTML autocomplete that should be displayed under the text input. request can be used, if set.

choices_for_values()[source]

Return the list of choices corresponding to values.

get_absolute_url()[source]

Return the absolute url for this autocomplete, using autocomplete_light_autocomplete url.

validate_values()[source]

Return True if values are all valid.

Rendering logic Autocomplete mixins

AutocompleteBase

class autocomplete_light.autocomplete.base.AutocompleteBase(request=None, values=None)[source]

A basic implementation of AutocompleteInterface that renders HTML and should fit most cases. It only needs overload of choices_for_request() and choices_for_values() which is the business-logic.

choice_html_format

HTML string used to format a python choice in HTML by choice_html(). It is formated with two positionnal parameters: the value and the html representation, respectively generated by choice_value() and choice_label(). Default is:

<span data-value="%s">%s</span>
empty_html_format

HTML string used to format the message “no matches found” if no choices match the current request. It takes a parameter for the translated message. Default is:

<span class="block"><em>%s</em></span>
autocomplete_html_format

HTML string used to format the list of HTML choices. It takes a positionnal parameter which contains the list of HTML choices which come from choice_html(). Default is:

%s
add_another_url_name

Name of the url to add another choice via a javascript popup. If empty then no “add another” link will appear.

add_another_url_kwargs

Keyword arguments to use when reversing the add another url.

widget_template

A special attribute used only by the widget. If it is set, the widget will use that instead of the default autocomplete_light/widget.html.

autocomplete_html()[source]

Simple rendering of the autocomplete.

It will append the result of choice_html() for each choice returned by choices_for_request(), and wrap that in autocomplete_html_format.

choice_html(choice)[source]

Format a choice using choice_html_format.

choice_label(choice)[source]

Return the human-readable representation of a choice. This simple implementation returns the textual representation.

choice_value(choice)[source]

Return the value of a choice. This simple implementation returns the textual representation.

choices_for_request()[source]

Return the list of choices that are available. Uses request if set, this method is used by autocomplete_html().

get_add_another_url()[source]

Return the url to use when adding another element

validate_values()[source]

This basic implementation returns True if all values are in choices_for_values().

AutocompleteTemplate

class autocomplete_light.autocomplete.template.AutocompleteTemplate(request=None, values=None)[source]

This extension of AutocompleteBase supports two new attributes:

choice_template

Name of the template to use to render a choice in the autocomplete. If none is specified, then AutocompleteBase will render the choice.

autocomplete_template

Name of the template to use to render the autocomplete. Again, fall back on AutocompleteBase if this is None.

autocomplete_html()[source]

Render autocomplete_template with base context and {{ choices }}. If autocomplete_template is None then fall back on base.AutocompleteBase.autocomplete_html().

choice_html(choice)[source]

Render choice_template with base context and {{ choice }}. If choice_template is None then fall back on base.AutocompleteBase.choice_html().

get_base_context()[source]

Return a dict to use as base context for all templates.

It contains:

  • {{ request }} if available,
  • {{ autocomplete }} the “self” instance.
render_template_context(template, extra_context=None)[source]

Render template with base context and extra_context.

Business logic Autocomplete mixins

AutocompleteList

class autocomplete_light.autocomplete.list.AutocompleteList[source]

Simple Autocomplete implementation which expects choices to be a list of string choices.

choices

List of string choices.

limit_choices

The maximum of items to suggest from choices.

order_by

order_choices() will use this against choices as an argument sorted().

It was mainly used as a starter for me when doing test-driven development and to ensure that the Autocomplete pattern would be concretely simple and yet powerful.

choices_for_request()[source]

Return any choices that contains the search string. It is case insensitive and ignores spaces.

choices_for_values()[source]

Return any choices that is in values.

order_choices(choices)[source]

Run sorted() against choices and order_by.

AutocompleteChoiceList

class autocomplete_light.autocomplete.choice_list.AutocompleteChoiceList[source]

Simple AutocompleteList implementation which expects choices to be a list of tuple choices in the fashion of django.db.models.Field.choices.

choices

List of choice tuples (value, label) like django.db.models.Field.choices. Example:

choices = (
    ('v', 'Video'),
    ('p', 'Paper'),
)
limit_choices

The maximum of items to suggest from choices.

order_by

order_choices() will use this against choices as an argument sorted().

choice_label(choice)[source]

Return item 1 of the choice tuple.

choice_value(choice)[source]

Return item 0 of the choice tuple.

choices_for_request()[source]

Return any choices tuple that contains the search string. It is case insensitive and ignores spaces.

choices_for_values()[source]

Return any choices that is in values.

AutocompleteModel

class autocomplete_light.autocomplete.model.AutocompleteModel[source]

Autocomplete which considers choices as a queryset.

choices

A queryset.

limit_choices

Maximum number of choices to display.

search_fields

Fields to search in, configurable like on django.contrib.admin.ModelAdmin.search_fields

split_words

If True, AutocompleteModel splits the search query into words and returns all objects that contain each of the words, case insensitive, where each word must be in at least one of search_fields. This mimics the mechanism of django’s django.contrib.admin.ModelAdmin.search_fields.

If ‘or’, AutocompleteModel does the same but returns all objects that contain any of the words.

order_by

If set, it will be used to order choices. It can be a single field name or an iterable (ie. list, tuple).

choice_label(choice)[source]

Return the textual representation of the choice by default.

choice_value(choice)[source]

Return the pk of the choice by default.

choices_for_request()[source]

Return a queryset based on choices using options split_words, search_fields and limit_choices.

choices_for_values()[source]

Return ordered choices which pk are in values.

order_choices(choices)[source]

Order choices using order_by option if it is set.

validate_values()[source]

Return True if all values where found in choices.

AutocompleteGeneric

class autocomplete_light.autocomplete.generic.AutocompleteGeneric[source]

AutocompleteModel extension which considers choices as a list of querysets, and composes a choice value with both the content type pk and the actual model pk.

choices

A list of querysets. Example:

choices = (
    User.objects.all(),
    Group.objects.all(),
)
search_fields

A list of lists of fields to search in, configurable like on ModelAdmin.search_fields. The first list of fields will be used for the first queryset in choices and so on. Example:

search_fields = (
    ('email', '^name'),  # Used for User.objects.all()
    ('name',)            # User for Group.objects.all()
)

AutocompleteGeneric inherits from model.AutocompleteModel and supports limit_choices and split_words exactly like AutocompleteModel.

However order_by is not supported (yet) in AutocompleteGeneric.

choice_value(choice)[source]

Rely on GenericModelChoiceField to return a string containing the content type id and object id of the result.

choices_for_request()[source]

Return a list of choices from every queryset in choices.

choices_for_values()[source]

Values which are not found in any querysets of choices are ignored.

validate_values()[source]

Ensure that every choice is part of a queryset in choices.

Autocomplete classes with both rendering and business logic

class autocomplete_light.autocomplete.AutocompleteChoiceListBase(request=None, values=None)[source]

Use AutocompleteBase for rendering logic and AutocompleteChoiceList for business logic.

class autocomplete_light.autocomplete.AutocompleteChoiceListTemplate(request=None, values=None)[source]

Use AutocompleteTemplate for rendering logic and AutocompleteChoiceList for business logic.

class autocomplete_light.autocomplete.AutocompleteGenericBase(request=None, values=None)[source]

Use AutocompleteBase for rendering logic and AutocompleteGeneric for business logic.

class autocomplete_light.autocomplete.AutocompleteGenericTemplate(request=None, values=None)[source]

Use AutocompleteTemplate for rendering logic and AutocompleteGeneric for business logic.

class autocomplete_light.autocomplete.AutocompleteListBase(request=None, values=None)[source]

Use AutocompleteBase for rendering logic and AutocompleteList for business logic.

class autocomplete_light.autocomplete.AutocompleteListTemplate(request=None, values=None)[source]

Use AutocompleteTemplate for rendering logic and AutocompleteList for business logic.

class autocomplete_light.autocomplete.AutocompleteModelBase(request=None, values=None)[source]

Use AutocompleteBase for rendering logic and AutocompleteModel for business logic.

class autocomplete_light.autocomplete.AutocompleteModelTemplate(request=None, values=None)[source]

Use AutocompleteTemplate for rendering logic and AutocompleteModel for business logic.

It also sets a default choice_template.

choice_template = 'autocomplete_light/model_template/choice.html'
class autocomplete_light.autocomplete.AutocompleteRestModelBase(request=None, values=None)[source]

Use AutocompleteBase for rendering logic and AutocompleteRestModel for business logic.

class autocomplete_light.autocomplete.AutocompleteRestModelTemplate(request=None, values=None)[source]

Use AutocompleteTemplate for rendering logic and AutocompleteRestModel for business logic.

Views

class autocomplete_light.views.AutocompleteView(**kwargs)[source]

Simple view that routes the request to the appropriate autocomplete.

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

get(request, *args, **kwargs)[source]

Return an HttpResponse with the return value of autocomplete.autocomplete_html().

This view is called by the autocomplete script, it is expected to return the rendered autocomplete box contents.

To do so, it gets the autocomplete class from the registry, given the url keyword argument autocomplete, that should be the autocomplete name.

Then, it instanciates the autocomplete with no argument as usual, and calls autocomplete.init_for_request, passing all arguments it recieved.

Finnaly, it makes an HttpResponse with the result of autocomplete.autocomplete_html(). The javascript will use that to fill the autocomplete suggestion box.

post(request, *args, **kwargs)[source]

Just proxy autocomplete.post().

This is the key to communication between the autocomplete and the widget in javascript. You can use it to create results and such.

class autocomplete_light.views.CreateView(**kwargs)[source]

Simple wrapper for generic.CreateView, that responds to _popup.

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

form_valid(form)[source]

If request.GET._popup, return some javascript.

Form, fields and widgets API

Widgets

WidgetBase

class autocomplete_light.widgets.WidgetBase(autocomplete=None, widget_js_attributes=None, autocomplete_js_attributes=None, extra_context=None, registry=None, widget_template=None, widget_attrs=None)[source]

Base widget for autocompletes.

attrs

HTML <input /> attributes, such as class, placeholder, etc ... Note that any data-autocomplete-* attribute will be parsed as an option for yourlabs.Autocomplete js object. For example:

attrs={
‘placeholder’: ‘foo’, ‘data-autocomplete-minimum-characters’: 0 ‘class’: ‘bar’,

}

Will render like::
<input
placeholder=”foo” data-autocomplete-minimum-characters=”0” class=”autocomplete bar”

/>

Which will set by the way yourlabs.Autocomplete.minimumCharacters option - the naming conversion is handled by jQuery.

widget_attrs

HTML widget container attributes. Note that any data-widget-* attribute will be parsed as an option for yourlabs.Widget js object. For example:

widget_attrs={
    'data-widget-maximum-values': 6,
    'class': 'country-autocomplete',
}

Will render like:

<span
    id="country-wrapper"
    data-widget-maximum-values="6"
    class="country-autocomplete autcomplete-light-widget"
/>

Which will set by the way yourlabs.Widget.maximumValues - note that the naming conversion is handled by jQuery.

widget_js_attributes

DEPRECATED in favor of :py:attr::widget_attrs.

A dict of options that will override the default widget options. For example:

widget_js_attributes = {'max_values': 8}

The above code will set this HTML attribute:

data-max-values="8"

Which will override the default javascript widget maxValues option (which is 0).

It is important to understand naming conventions which are sparse unfortunately:

  • python: lower case with underscores ie. max_values,
  • HTML attributes: lower case with dashes ie. data-max-values,
  • javascript: camel case, ie. maxValues.

The python to HTML name conversion is done by the autocomplete_light_data_attributes template filter.

The HTML to javascript name conversion is done by the jquery plugin.

autocomplete_js_attributes

DEPRECATED in favor of :py:attr::attrs.

A dict of options like for widget_js_attributes. However, note that HTML attributes will be prefixed by data-autocomplete- instead of just data-. This allows the jQuery plugins to make the distinction between attributes for the autocomplete instance and attributes for the widget instance.

extra_context

Extra context dict to pass to the template.

widget_template

Template to use to render the widget. Default is autocomplete_light/widget.html.

ChoiceWidget

class autocomplete_light.widgets.ChoiceWidget(autocomplete=None, widget_js_attributes=None, autocomplete_js_attributes=None, extra_context=None, registry=None, widget_template=None, widget_attrs=None, *args, **kwargs)[source]

Widget that provides an autocomplete for zero to one choice.

MultipleChoiceWidget

class autocomplete_light.widgets.MultipleChoiceWidget(autocomplete=None, widget_js_attributes=None, autocomplete_js_attributes=None, extra_context=None, registry=None, widget_template=None, widget_attrs=None, *args, **kwargs)[source]

Widget that provides an autocomplete for zero to n choices.

TextWidget

class autocomplete_light.widgets.TextWidget(autocomplete=None, widget_js_attributes=None, autocomplete_js_attributes=None, extra_context=None, registry=None, widget_template=None, widget_attrs=None, *args, **kwargs)[source]

Widget that just adds an autocomplete to fill a text input.

Note that it only renders an <input>, so attrs and widget_attrs are merged together.

render(name, value, attrs=None)[source]

Proxy Django’s TextInput.render()

Fields

FieldBase

class autocomplete_light.fields.FieldBase(autocomplete=None, registry=None, widget=None, widget_js_attributes=None, autocomplete_js_attributes=None, extra_context=None, *args, **kwargs)[source]

ChoiceField

class autocomplete_light.fields.ChoiceField(autocomplete=None, registry=None, widget=None, widget_js_attributes=None, autocomplete_js_attributes=None, extra_context=None, *args, **kwargs)[source]
widget

alias of ChoiceWidget

MultipleChoiceField

class autocomplete_light.fields.MultipleChoiceField(autocomplete=None, registry=None, widget=None, widget_js_attributes=None, autocomplete_js_attributes=None, extra_context=None, *args, **kwargs)[source]
widget

alias of MultipleChoiceWidget

ModelChoiceField

class autocomplete_light.fields.ModelChoiceField(autocomplete=None, registry=None, widget=None, widget_js_attributes=None, autocomplete_js_attributes=None, extra_context=None, *args, **kwargs)[source]
widget

alias of ChoiceWidget

ModelMultipleChoiceField

class autocomplete_light.fields.ModelMultipleChoiceField(autocomplete=None, registry=None, widget=None, widget_js_attributes=None, autocomplete_js_attributes=None, extra_context=None, *args, **kwargs)[source]
widget

alias of MultipleChoiceWidget

GenericModelChoiceField

class autocomplete_light.fields.GenericModelChoiceField(autocomplete=None, registry=None, widget=None, widget_js_attributes=None, autocomplete_js_attributes=None, extra_context=None, *args, **kwargs)[source]

Simple form field that converts strings to models.

prepare_value(value)[source]

Given a model instance as value, with content type id of 3 and pk of 5, return such a string ‘3-5’.

to_python(value)[source]

Given a string like ‘3-5’, return the model of content type id 3 and pk 5.

widget

alias of ChoiceWidget

GenericModelMultipleChoiceField

class autocomplete_light.fields.GenericModelMultipleChoiceField(autocomplete=None, registry=None, widget=None, widget_js_attributes=None, autocomplete_js_attributes=None, extra_context=None, *args, **kwargs)[source]

Simple form field that converts strings to models.

widget

alias of MultipleChoiceWidget

Form stuff

High-level API for django-autocomplete-light.

Before, django-autocomplete-light was just a container for a loosely coupled set of tools. You had to go for a treasure hunt in the docs and source to find just what you need and add it to your project.

While you can still do that, this module adds a high-level API which couples all the little pieces together. Basically you could just inherit from ModelForm or use modelform_factory() and expect everything to work out of the box, from simple autocompletes to generic many to many autocompletes including a bug fix for django bug #9321 or even added security.

modelform_factory

autocomplete_light.forms.modelform_factory(model, autocomplete_fields=None, autocomplete_exclude=None, autocomplete_names=None, registry=None, **kwargs)[source]

Wrap around Django’s django_modelform_factory, using our ModelForm and setting autocomplete_fields and autocomplete_exclude.

ModelForm

class autocomplete_light.forms.ModelForm(*args, **kwargs)[source]

ModelForm override using our metaclass that adds our various mixins.

autocomplete_fields

A list field names on which you want automatic autocomplete fields.

autocomplete_exclude

A list of field names on which you do not want automatic autocomplete fields.

autocomplete_names

A dict of field_name: AutocompleteName to override the default autocomplete that would be used for a field.

Note: all of autocomplete_fields, autocomplete_exclude and autocomplete_names understand generic foreign key and generic many to many descriptor names.

ModelFormMetaclass

class autocomplete_light.forms.ModelFormMetaclass[source]

Wrap around django’s ModelFormMetaclass to add autocompletes.

SelectMultipleHelpTextRemovalMixin

class autocomplete_light.forms.SelectMultipleHelpTextRemovalMixin(*args, **kwargs)[source]

This mixin that removes the ‘Hold down “Control” ...’ message that is enforced in select multiple fields.

See https://code.djangoproject.com/ticket/9321

VirtualFieldHandlingMixin

class autocomplete_light.forms.VirtualFieldHandlingMixin(*args, **kwargs)[source]

Enable virtual field (generic foreign key) handling in django’s ModelForm.

  • treat virtual fields like GenericForeignKey as normal fields,
  • when setting a GenericForeignKey value, also set the object id and content type id fields.

Probably, django doesn’t do that for legacy reasons: virtual fields were added after ModelForm and simply nobody asked django to add virtual field support in ModelForm.

The constructor adds virtual field values to django.forms.Form.initial

GenericM2MRelatedObjectDescriptorHandlingMixin

class autocomplete_light.forms.GenericM2MRelatedObjectDescriptorHandlingMixin(*args, **kwargs)[source]

Extension of autocomplete_light.GenericModelForm, that handles genericm2m’s RelatedObjectsDescriptor.

Add related objects to initial for each generic m2m field.

generic_m2m_fields()[source]

Yield name, field for each RelatedObjectsDescriptor of the model of this ModelForm.

save(commit=True)[source]

Save the form and particularely the generic many to many relations.

FormfieldCallback

class autocomplete_light.forms.FormfieldCallback(default=None, meta=None)[source]

Decorate model_field.formfield() to use a autocomplete_light.ModelChoiceField for OneToOneField and ForeignKey or a autocomplete_light.ModelMultipleChoiceField for a ManyToManyField.

It is the very purpose of our ModelFormMetaclass !

ModelFormMetaclass

class autocomplete_light.forms.ModelFormMetaclass[source]

Wrap around django’s ModelFormMetaclass to add autocompletes.

Script API

autocomplete.js

The autocomplete box script, see autocomplete.js API documentation.

widget.js

The script that ties the autocomplete box script and the hidden <select> used by django, see widget.js API documentation.

text_widget.js

The script that ties the autocomplete box script with a text input, see text_widget.js API docummentation.

addanother.js

The script that enables adding options to a <select> outside the admin, see addanother.js API documentation.

remote.js

The script that overrides a method from widget.js to create choices on the fly, see remote.js API documentation.