Registry

The registry module provides tools to maintain a registry of autocompletes.

The first thing that should happen when django starts is registration of autocompletes. It should happen first, because autocompletes are required for widgets. And autocomplete widgets are required for forms. And forms are required for ModelAdmin.

It looks like this:

autocomplete_light.registry.registry

Module-level instance of AutocompleteRegistry.

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 pass a custom base autocomplete which will be set to autocomplete_model_base when instanciating an AutocompleteRegistry.

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.

Autocompletes

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.

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 class="div" 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="div"><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.

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().

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.

Other Autocompletes

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

Use AutocompleteBase 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.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.

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 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. 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).

x.__init__(...) initializes x; see help(type(x)) for signature

choice_label(choice)[source]

Return the unicode 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. Refer to the class-level documentation for documentation on each of these options.

choices_for_values()[source]

Return ordered choices which pk are in self.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]

Autocomplete which considers choices as a list of querysets. It inherits from AutocompleteModel so make sure that you’ve read the docs and docstrings for AutocompleteModel before using this class.

choices
A list of querysets.
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.

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

However order_by is not supported (yet) in AutocompleteGeneric.

x.__init__(...) initializes x; see help(type(x)) for signature

choice_value(choice)[source]

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

Because this autocomplete is made for that field, and to avoid code duplication.

choices_for_request()[source]

Propose local results and fill the autocomplete with remote suggestions.

choices_for_values()[source]

Values which are not found in the querysets are ignored.

validate_values()[source]

Ensure that every choice is part of a queryset.

import autocomplete_light

See everything available in autocomplete_light/__init__.py:

"""
Provide tools to enable nice autocompletes in your Django project.
"""
from .registry import AutocompleteRegistry, registry, register, autodiscover
from .autocomplete import *
from .widgets import ChoiceWidget, MultipleChoiceWidget, TextWidget
from .forms import get_widgets_dict, modelform_factory, FixedModelForm
from .generic import GenericModelForm, GenericModelChoiceField
from .views import CreateView
from .exceptions import AutocompleteNotRegistered

ModelForm = FixedModelForm

Widgets

ChoiceWidget is intended to work as a replacement for django’s Select widget, and MultipleChoiceWidget for django’s SelectMultiple.

Constructing a widget needs an Autocomplete class or registered autocomplete name.

The choice autocomplete widget renders from autocomplete_light/widget.html template.

WidgetBase

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

Base widget for autocompletes.

Mainly handles passing arguments from Python to HTML data-* attributes, via widget_js_attributes and autocomplete_js_attributes. Javascript will parse these data-* attributes.

This widget also renders the widget template.

ChoiceWidget

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

Base widget for autocompletes.

Mainly handles passing arguments from Python to HTML data-* attributes, via widget_js_attributes and autocomplete_js_attributes. Javascript will parse these data-* attributes.

This widget also renders the widget template.

MultipleChoiceWidget

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

Widget that provides an autocomplete for zero to n choices.

TextWidget

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

Widget that just adds an autocomplete to fill a text input

Form shortcuts

A couple of helper functions to help enabling Widget in ModelForms.

autocomplete_light.forms.get_widgets_dict(model, autocomplete_exclude=None, registry=None)[source]

Return a dict of field_name: widget_instance for model that is compatible with Django.

autocomplete_exclude
List of model field names to ignore
registry
Registry to use.

Inspect the model’s field and many to many fields, calls registry.autocomplete_for_model to get the autocomplete for the related model. If a autocomplete is returned, then an Widget will be spawned using this autocomplete.

The dict is usable by ModelForm.Meta.widgets. In django 1.4, with modelform_factory too.

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

Wraps around Django’s django_modelform_factory, using get_widgets_dict.

autocomplete_exclude
List of model field names to ignore
registry
Registry to use.

Basically, it will use the dict returned by get_widgets_dict in order and pass it to django’s modelform_factory, and return the resulting modelform.

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

Simple child of FixedModelForm that removes the ‘Hold down “Control” ...’ message that is enforced in select multiple fields. Added in 1.0.23.

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

Views

RegistryView

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

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

AutocompleteView

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.

CreateView

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.

Generic foreign key support

class autocomplete_light.generic.GenericModelForm(*args, **kwargs)[source]

This simple subclass of ModelForm fixes a couple of issues with django’s ModelForm.

  • treat virtual fields like GenericForeignKey as normal fields, Django should already do that but it doesn’t,
  • when setting a GenericForeignKey value, also set the object id and content type id fields, again Django could probably afford to do that.

What ModelForm does, but also add virtual field values to self.initial.

class autocomplete_light.generic.GenericModelChoiceField(required=True, widget=None, label=None, initial=None, help_text=u'', error_messages=None, show_hidden_initial=False, validators=[], localize=False)[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.

autocomplete_light.contrib.generic_m2m

autocomplete_light.contrib.generic_m2m couples django-autocomplete-light with django-generic-m2m.

Generic many to many are supported since 0.5. It depends on django-generic-m2m external apps. Follow django-generic-m2m installation documentation, but at the time of writing it barely consists of adding the genericm2m to INSTALLED_APPS, and adding a field to models that should have a generic m2m relation. So, kudos to the maintainers of django-generic-m2m, fantastic app, use it for generic many to many relations.

See examples in test_project/generic_m2m_example.

class autocomplete_light.contrib.generic_m2m.GenericModelForm(*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.

class autocomplete_light.contrib.generic_m2m.GenericModelMultipleChoiceField(required=True, widget=None, label=None, initial=None, help_text=u'', error_messages=None, show_hidden_initial=False, validators=[], localize=False)[source]

Simple form field that converts strings to models.

autocomplete_light.contrib.taggit_tagfield

Support for django-taggit tags system. If using django-taggit, you will need this.

Example usage:

from autocomplete_light.contrib.taggit_tagfield import TagField, TagWidget

class AppEditForm(forms.ModelForm):
    tags = TagField(widget=TagWidget('TagAutocomplete'))

Warning

In this case, the tags field is a relation. Thus form.save() must be called with commit=True.