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.shortcuts as al al.registry.autocomplete_model_base = al.AutocompleteModelTemplate al.autodiscover()
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.
-
-
autocomplete_light.registry.
register
(*args, **kwargs)[source]¶ Proxy method
AutocompleteRegistry.register()
of theregistry
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 ofregister()
statements in that module, filling upregistry
.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.shortcuts as al al.register(City) al.register(Country)
When
autodiscover()
importscities_light.autocomplete_light_registry
, bothCityAutocomplete
andCountryAutocomplete
will be registered. SeeAutocompleteRegistry.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()
andchoices_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 ofAutocompleteInterface
.Instanciate an Autocomplete with a given
request
andvalues
arguments.values
will be casted to list if necessary and both will be assigned to instance attributesrequest
andvalues
respectively.-
autocomplete_html
()[source]¶ Return the HTML autocomplete that should be displayed under the text input.
request
can be used, if set.
-
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()
andchoices_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 bychoice_value()
andchoice_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 bychoices_for_request()
, and wrap that inautocomplete_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 byautocomplete_html()
.
-
validate_values
()[source]¶ This basic implementation returns True if all
values
are inchoices_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 }}
. Ifautocomplete_template
is None then fall back onbase.AutocompleteBase.autocomplete_html()
.
-
choice_html
(choice)[source]¶ Render
choice_template
with base context and{{ choice }}
. Ifchoice_template
is None then fall back onbase.AutocompleteBase.choice_html()
.
-
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.
-
order_by
¶ order_choices()
will use this againstchoices
as an argumentsorted()
.
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.
-
AutocompleteChoiceList¶
-
class
autocomplete_light.autocomplete.choice_list.
AutocompleteChoiceList
[source]¶ Simple
AutocompleteList
implementation which expectschoices
to be a list of tuple choices in the fashion ofdjango.db.models.Field.choices
.-
choices
¶ List of choice tuples
(value, label)
likedjango.db.models.Field.choices
. Example:choices = ( ('v', 'Video'), ('p', 'Paper'), )
-
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 in the deck. It can be a single field name or an iterable (ie. list, tuple). However, if AutocompleteModel is instanciated with a list of values, it’ll reproduce the ordering of values.
-
choices_for_request
()[source]¶ Return a queryset based on
choices
using optionssplit_words
,search_fields
andlimit_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 supportslimit_choices
andsplit_words
exactly like AutocompleteModel.However
order_by
is not supported (yet) in AutocompleteGeneric.-
Autocomplete classes with both rendering and 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.
-
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 anydata-autocomplete-*
attribute will be parsed as an option foryourlabs.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 foryourlabs.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.
- python: lower case with underscores ie.
-
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 bydata-autocomplete-
instead of justdata-
. 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¶
MultipleChoiceWidget¶
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.
Fields¶
FieldBase¶
ChoiceField¶
MultipleChoiceField¶
ModelChoiceField¶
ModelMultipleChoiceField¶
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¶
ModelForm¶
-
class
autocomplete_light.forms.
ModelForm
(*args, **kwargs)[source]¶ ModelForm override using our metaclass that adds our various mixins.
-
autocomplete_fields
¶ A list of 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
andautocomplete_names
understand generic foreign key and generic many to many descriptor names.-
ModelFormMetaclass¶
SelectMultipleHelpTextRemovalMixin¶
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
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 !
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.