Django Autocomplete Light
Django Autocomplete Light
Documentation
Release 3.2.9
1 Features 1
2 Upgrading 3
3 Resources 5
4 Basics 7
4.1 Install django-autocomplete-light v3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
4.2 django-autocomplete-light tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
6 API 27
6.1 dal: django-autocomplete-light3 API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
6.2 FutureModelForm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
6.3 dal_select2: Select2 support for DAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
6.4 dal_contenttypes: GenericForeignKey support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
6.5 dal_select2_queryset_sequence: Select2 for QuerySetSequence choices . . . . . . . . . . . . . . . . 33
6.6 dal_queryset_sequence: QuerySetSequence choices . . . . . . . . . . . . . . . . . . . . . . . . . . 34
6.7 dal_gm2m_queryset_sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
6.8 dal_genericm2m_queryset_sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
6.9 dal_gm2m: django-gm2m support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
6.10 dal_genericm2m: django-genericm2m support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
6.11 dal_select2_taggit: django-taggit support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
6.12 dal_select2_tagging: django-tagging support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
i
ii
CHAPTER 1
Features
1
django-autocomplete-light Documentation, Release 3.2.9
2 Chapter 1. Features
CHAPTER 2
Upgrading
See CHANGELOG..
For v2 users and experts, a blog post was published with plenty of details.
3
django-autocomplete-light Documentation, Release 3.2.9
4 Chapter 2. Upgrading
CHAPTER 3
Resources
5
django-autocomplete-light Documentation, Release 3.2.9
6 Chapter 3. Resources
CHAPTER 4
Basics
Install django-autocomplete-light v3
Then, let Django find static file we need by adding to INSTALLED_APPS, before django.contrib.admin and
grappelli if present:
'dal',
'dal_select2',
# 'grappelli',
'django.contrib.admin',
This is to override the jquery.init.js script provided by the admin, which sets up jQuery with noConflict,
making jQuery available in django.jQuery only and not $.
To enable more DAL functionalities we will have to add other DAL apps to INSTALLED_APPS, such as
dal_queryset_sequence ...
Note: If you are trying to install from git, please make sure you are not using zip/archive url of the repo
django-autocomplete-light since it will not contain required submodules automatically. Otherwise these
submodules will then need to be updated separately using git submodule update --init.
7
django-autocomplete-light Documentation, Release 3.2.9
cd /tmp
virtualenv dal_env
source dal_env/bin/activate
pip install django
pip install -e git+https://github.com/yourlabs/django-autocomplete-light.git
#egg=django-autocomplete-light
cd dal_env/src/django-autocomplete-light/test_project/
pip install -r requirements.txt
./manage.py migrate
./manage.py createsuperuser
./manage.py runserver
# go to http://localhost:8000/admin/ and login
django-autocomplete-light tutorial
Overview
Note: Do not miss the Classy Class-Based Views website which helps a lot to work with class-based views in general.
In this tutorial, well first learn to make autocompletes backed by a QuerySet. Suppose we have a Country Model
which we want to provide a Select2 autocomplete widget for in a form. If a users types an f it would propose Fiji,
Finland and France, to authenticated users only:
8 Chapter 4. Basics
django-autocomplete-light Documentation, Release 3.2.9
class CountryAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
# Don't forget to filter out results depending on the visitor !
if not self.request.user.is_authenticated():
return Country.objects.none()
qs = Country.objects.all()
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
Note: For more complex filtering, refer to official documentation for the QuerySet API.
urlpatterns = [
url(
r'^country-autocomplete/$',
CountryAutocomplete.as_view(),
name='country-autocomplete',
),
]
./manage.py shell
In [1]: from django.urls import reverse
In [2]: #older django versions: from django.core.urlresolvers import reverse
In [3]: reverse('country-autocomplete')
Out[2]: u'/country-autocomplete/'
Danger: As you might have noticed, we have just exposed data through a public URL. Please dont forget to do
proper permission checks in get_queryset.
We can now use the autocomplete view our Person form, for its birth_country field thats a ForeignKey. So,
were going to override the default ModelForm fields, to use a widget to select a Model with Select2,
in our case by passing the name of the url we have just registered to ModelSelect2.
One way to do it is by overriding the form field, ie:
class PersonForm(forms.ModelForm):
birth_country = forms.ModelChoiceField(
queryset=Country.objects.all(),
widget=autocomplete.ModelSelect2(url='country-autocomplete')
)
class Meta:
model = Person
fields = ('__all__')
Another way to do this is directly in the Form.Meta.widgets dict, if overriding the field is not needed:
class PersonForm(forms.ModelForm):
class Meta:
model = Person
fields = ('__all__')
widgets = {
'birth_country': autocomplete.ModelSelect2(url='country-autocomplete')
}
If we need the country autocomplete view for a widget used for a ManyToMany relation instead of a ForeignKey, with
a model like that:
10 Chapter 4. Basics
django-autocomplete-light Documentation, Release 3.2.9
class Person(models.Model):
visited_countries = models.ManyToManyField('your_countries_app.country')
widgets = {
'visited_countries': autocomplete.ModelSelect2Multiple(url='country-autocomplete')
}
Select2 supports a bunch of options. These options may be set in data-* attributes. For example:
Note: Setting a placeholder will result in generation of an an empty option tag, which select2 requires.
class PersonAdmin(admin.ModelAdmin):
form = PersonForm
admin.site.register(Person, PersonAdmin)
class PersonInline(admin.TabularInline):
model = Person
form = PersonForm
{% block content %}
<div>
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" />
</form>
</div>
{% endblock %}
{% block footer %}
<script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}">
</script>
{{ form.media }}
{% endblock %}
You can display custom HTML code for results by setting the data-html attribute on your widget and overriding
the view get_result_label() method to return HTML code.
class CountryAutocomplete(autocomplete.Select2QuerySetView):
def get_result_label(self, item):
return '<img src="flags/%s.png"> %s' % (item.name, item.name)
class PersonForm(forms.ModelForm):
class Meta:
widgets = {
'birth_country': autocomplete.ModelSelect2(
url='country-autocomplete',
attrs={'data-html': True}
)
}
Note: Take care to escape anything you put in HTML code to avoid XSS attacks when displaying data that may have
been input by a user!
12 Chapter 4. Basics
django-autocomplete-light Documentation, Release 3.2.9
data-autocomplete-light-function both on page load and DOM node insertion. It also keeps
track of initialized elements to prevent double-initialization.
Take dal_select2 for example, it is initialized by dal_select2/static/autocomplete_light/
select2.js as such:
$(document).on('autocompleteLightInitialize', '[data-autocomplete-light-
function=select2]', function() {
class YourWidget(ModelSelect2):
autocomplete_function = 'your-autocomplete-function'
Example script:
$(document).on(
'autocompleteLightInitialize',
'[data-autocomplete-light-function=your-autocomplete-function]',
function() {
// do your own script setup here
})
This allows the user to create objects on the fly from within the AJAX widget. When the user selects that option, the
autocomplete script will make a POST request to the view. It should create the object and return the pk, so the item
will then be added just as if it already had a PK:
To enable this, first the view must know how to create an object given only self.q, which is the variable containing
the user input in the view. Set the create_field view option to enable creation of new objects from within the
autocomplete user interface, ie:
urlpatterns = [
url(
r'^country-autocomplete/$',
CountryAutocomplete.as_view(create_field='name'),
name='country-autocomplete',
),
]
This way, the option Create Tibet will be available if a user inputs Tibet for example. When the user clicks it, it
will make the post request to the view which will do Country.objects.create(name='Tibet'). It will be
included in the server response so that the script can add it to the widget.
Note that creating objects is only allowed to staff users with add permission by default.
But if you select test as an owner, and open the autocomplete again, youll only see the option with owner=test:
14 Chapter 4. Basics
django-autocomplete-light Documentation, Release 3.2.9
Lets say we want to add a Continent choice field in the form, and filter the countries based on the value on this
field. We then need the widget to pass the value of the continent field to the view when it fetches data. We can use the
forward widget argument to do this:
class PersonForm(forms.ModelForm):
continent = forms.ChoiceField(choices=CONTINENT_CHOICES)
class Meta:
model = Person
fields = ('__all__')
widgets = {
'birth_country': autocomplete.ModelSelect2(url='country-autocomplete',
forward=['continent'])
}
DALs Select2 configuration script will get the value fo the form field named 'continent' and add it to the auto-
complete HTTP query. This will pass the value for the continent form field in the AJAX request, and we can then
filter as such in the view:
class CountryAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated():
return Country.objects.none()
qs = Country.objects.all()
if continent:
qs = qs.filter(continent=continent)
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
Lets assume that you have the following form using linked autocomplete fields:
class ShippingForm(forms.Form):
src_continent = forms.ModelChoiceField(
queryset=Continent.objects.all(),
widget=autocomplete.ModelSelect2(url='continent-autocomplete'))
src_country = forms.ModelChoiceField(
queryset=Country.objects.all(),
widget=autocomplete.ModelSelect2(
url='country-autocomplete',
forward=('src_continent',)))
class CountryAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.is_authenticated():
return Country.objects.none()
qs = Country.objects.all()
if continent:
qs = qs.filter(continent=continent)
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
You cannot use this autocomplete view together with your form because the name forwarded from the form differs
from the name that autocomplete view expects.
You can rename forwarded fields using class-based forward declaration to pass src_continent value as continent:
class ShippingForm(forms.Form):
src_continent = forms.ModelChoiceField(
queryset=Continent.objects.all(),
widget=autocomplete.ModelSelect2(url='continent-autocomplete'))
src_country = forms.ModelChoiceField(
queryset=Country.objects.all(),
widget=autocomplete.ModelSelect2(
url='country-autocomplete',
forward=(forward.Field('src_continent', 'continent'),)))
some_field = forms.ModelChoiceField(
queryset=SomeModel.objects.all(),
widget=autocomplete.ModelSelect2(
url='some-autocomplete',
forward=(
'f1', # String based declaration
forward.Field('f2'), # Works the same way as above declaration
forward.Field('f3', 'field3'), # With rename
16 Chapter 4. Basics
django-autocomplete-light Documentation, Release 3.2.9
The other thing you can do with class-based forwarding declaration is to forward an arbitrary constant without adding
extra hidden fields to your form.
class EuropeanShippingForm(forms.Form):
src_country = forms.ModelChoiceField(
queryset=Country.objects.all(),
widget=autocomplete.ModelSelect2(
url='country-autocomplete',
forward=(forward.Const('europe', 'continent'),)))
You can use the $.getFormPrefix() jQuery plugin used by DAL to clear the birth_country autocomplete
widget from the above example when the continent field changes with such a snippet:
$(document).ready(function() {
// Bind on continent field change
$(':input[name$=continent]').on('change', function() {
// Get the field prefix, ie. if this comes from a formset form
var prefix = $(this).getFormPrefix();
To autoload the script with the form, you can use Form.Media.
Sometimes it is useful to specify autocomplete choices based on a list of strings rather than a QuerySet. This can be
achieved with the Select2ListView class:
class CountryAutocompleteFromList(autocomplete.Select2ListView):
def get_list(self):
return ['France', 'Fiji', 'Finland', 'Switzerland']
This class can then be registered as in the previous example. Suppose we register it under URL country-list-
autocomplete. We can then a create a ListSelect2 widget with:
widget = autocomplete.ListSelect2(url='country-list-autocomplete')
With this in place, if a user types the letter f in the widget, choices France, Fiji, and Finland would be offered.
Like the Select2QuerySetView, the Select2ListView is case insensitive.
def get_choice_list():
return ['France', 'Fiji', 'Finland', 'Switzerland']
class CountryForm(forms.ModelForm):
country = autocomplete.Select2ListChoiceField(
choice_list=get_choice_list,
widget=autocomplete.ListSelect2(url='country-list-autocomplete')
)
Since the selections in Select2ListView map directly to a list, there is no built-in support for choices in a ChoiceField
that do not have the same value for every text. Select2ListCreateChoiceField allows you to provide custom
text from a Select2List widget and should be used if you define Select2ListViewAutocomplete.create.
It is better to use the same source for Select2ListViewAutocomplete.get_list in your view and the
Select2ListChoiceField choice_list kwarg to avoid unexpected behavior.
An opt-group version is available in a similar fashion by inheriting Select2GroupListView :
class CountryAutocompleteFromList(autocomplete.Select2GroupListView):
def get_list(self):
return [
("Country", ['France', 'Fiji', 'Finland', 'Switzerland'])
]
18 Chapter 4. Basics
CHAPTER 5
Model example
class TestModel(models.Model):
name = models.CharField(max_length=200)
content_type = models.ForeignKey(
'contenttypes.ContentType',
null=True,
blank=True,
editable=False,
)
object_id = models.PositiveIntegerField(
null=True,
blank=True,
editable=False,
)
def __str__(self):
return self.name
19
django-autocomplete-light Documentation, Release 3.2.9
class LocationAutocompleteView(Select2QuerySetSequenceView):
def get_queryset(self):
countries = Country.objects.all()
cities = City.objects.all()
if self.q:
countries = countries.filter(continent__incontains=self.q)
cities = cities.filter(country__name__icontains=self.q)
# Aggregate querysets
qs = QuerySetSequence(countries, cities)
if self.q:
# This would apply the filter on all the querysets
qs = qs.filter(name__icontains=self.q)
# This will limit each queryset so that they show an equal number
# of results.
qs = self.mixup_querysets(qs)
return qs
urlpatterns = [
url(
r'^location-autocomplete/$',
LocationAutocompleteView.as_view(),
name='location-autocomplete'
),
]
Form example
As usual, we need a backend-aware widget that will make only selected choices to render initially, to avoid butchering
the database. As were using a QuerySetSequence and Select2, well try QuerySetSequenceSelect2 widget.
Also, we need a field thats able to use a QuerySetSequence for choices to do validation on a single model choice,
well use QuerySetSequenceModelField.
Finnaly, we cant use Djangos ModelForm because it doesnt support non-editable fields, which GenericForeignKey
is. Instead, well use FutureModelForm.
Result:
class TestForm(autocomplete.FutureModelForm):
location = dal_queryset_sequence.fields.QuerySetSequenceModelField(
queryset=autocomplete.QuerySetSequence(
Country.objects.all(),
City.objects.all(),
),
required=False,
widget=dal_select2_queryset_sequence.widgets.QuerySetSequenceSelect2(
'location-autocomplete'),
class Meta:
model = TestModel
Model example
class TestModel(models.Model):
name = models.CharField(max_length=200)
locations = GM2MField()
def __str__(self):
return self.name
View example
The View example for QuerySetSequence and Select2 works here too: were relying on Select2 and QuerySetSequence
again.
Form example
As usual, we need a backend-aware widget that will make only selected choices to render ini-
tially, to avoid butchering the database. As were using a QuerySetSequence and Select2, well try
QuerySetSequenceSelect2Multiple widget.
Also, we need a field thats able to use a QuerySetSequence for choices to validate multiple models, and then update
the GM2MField relations: GM2MQuerySetSequenceField.
Finnaly, we cant use Djangos ModelForm because it doesnt support non-editable fields, which GM2MField is.
Instead, well use FutureModelForm.
Example:
class TestForm(autocomplete.FutureModelForm):
locations = autocomplete.GM2MQuerySetSequenceField(
queryset=autocomplete.QuerySetSequence(
Country.objects.all(),
City.objects.all(),
),
required=False,
widget=autocomplete.QuerySetSequenceSelect2Multiple(
'location-autocomplete'),
)
class Meta:
model = TestModel
fields = ('name',)
Model example
class TestModel(models.Model):
name = models.CharField(max_length=200)
locations = RelatedObjectsDescriptor()
def __str__(self):
return self.name
View example
The View example for QuerySetSequence and Select2 works here too: were relying on Select2 and QuerySetSequence
again.
Form example
As usual, we need a backend-aware widget that will make only selected choices to render initially, to avoid
butchering the database. As were using a QuerySetSequence and Select2 for multiple selections, well try
QuerySetSequenceSelect2Multiple widget.
Also, we need a field thats able to use a QuerySetSequence for choices to validate multiple models, and then update
the RelatedObjectsDescriptor relations: GenericM2MQuerySetSequenceField.
Finnaly, we cant use Djangos ModelForm because it doesnt support non-editable fields, which RelatedObjectsDe-
scriptor is. Instead, well use FutureModelForm.
Example:
class TestForm(autocomplete.FutureModelForm):
locations = autocomplete.GenericM2MQuerySetSequenceField(
queryset=autocomplete.QuerySetSequence(
Country.objects.all(),
City.objects.all(),
),
required=False,
widget=autocomplete.QuerySetSequenceSelect2Multiple(
'location-autocomplete'),
)
class Meta:
model = TestModel
fields = ('name',)
Model example
class TestModel(models.Model):
name = models.CharField(max_length=200)
tags = TagField()
def __str__(self):
return self.name
View example
The QuerySet view works here too: were relying on Select2 and a QuerySet of Tag objects:
class TagAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
# Don't forget to filter out results depending on the visitor !
if not self.request.user.is_authenticated():
return Tag.objects.none()
qs = Tag.objects.all()
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
Form example
As usual, we need a backend-aware widget that will make only selected choices to render initially, to avoid butchering
the database.
As were using a QuerySet of Tag and Select2 in its tag appearance, well use TaggitSelect2. It is compatible
with the default form field created by the model field: TagField.
Example:
class TestForm(autocomplete.FutureModelForm):
class Meta:
model = TestModel
fields = ('name',)
widgets = {
'tags': autocomplete.TaggingSelect2(
'your-taggit-autocomplete-url'
)
}
Model example
class TestModel(models.Model):
name = models.CharField(max_length=200)
tags = TaggableManager()
def __str__(self):
return self.name
View example
The QuerySet view works here too: were relying on Select2 and a QuerySet of Tag objects:
class TagAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
# Don't forget to filter out results depending on the visitor !
if not self.request.user.is_authenticated():
return Tag.objects.none()
qs = Tag.objects.all()
if self.q:
qs = qs.filter(name__istartswith=self.q)
return qs
Note: For more complex filtering, refer to official documentation for the QuerySet API.
Form example
As usual, we need a backend-aware widget that will make only selected choices to render initially, to avoid butchering
the database.
As were using a QuerySet of Tag and Select2 in its tag appearance, well use TaggitSelect2. It is compat-
ible with the default form field created by the model field: TaggeableManager - which actually inherits django.
db.models.fields.Field and django.db.models.fields.related.RelatedField and not from
django.db.models.Manager.
Example:
class TestForm(autocomplete.FutureModelForm):
class Meta:
model = TestModel
fields = ('name',)
widgets = {
'tags': autocomplete.TaggitSelect2(
'your-taggit-autocomplete-url'
)
}
API
Views
27
django-autocomplete-light Documentation, Release 3.2.9
class dal.views.ViewMixin
Common methods for autocomplete views.
It is assumed this view will be used in conjunction with a Django View based class that will that will implement
OPTIONS.
forwarded
Dict of field values that were forwarded from the form, may be used to filter autocompletion results based
on the form state. See linked_data example for reference.
q
Query string as typed by the user in the autocomplete field.
dispatch(request, *args, **kwargs)
Set forwarded and q.
Widgets
28 Chapter 6. API
django-autocomplete-light Documentation, Release 3.2.9
filter_choices_to_render(selected_choices)
Replace self.choices with selected_choices.
optgroups(name, value, attrs=None)
Exclude unselected self.choices before calling the parent method.
Used by Django>=1.10.
render(name, value, attrs=None)
Calling Django render together with render_forward_conf.
render_forward_conf(id)
Render forward configuration for the field.
render_options(*args)
Django-compatibility method for option rendering.
Should only render selected options, by setting self.choices before calling the parent method.
Remove this code when dropping support for Django<1.10.
Fields
FutureModelForm
6.2. FutureModelForm 29
django-autocomplete-light Documentation, Release 3.2.9
a generic foreign key only sets instance attributes, its form field would do that in save_object_data(),
a tag field saves relations, its form field would do that in save_relation_data().
class dal.forms.FutureModelForm(*args, **kwargs)
ModelForm which adds extra API to form fields.
Form fields may define new methods for FutureModelForm:
FormField.value_from_object(instance, name) should return the initial value to use in
the form, overrides ModelField.value_from_object() which is what ModelForm uses by de-
fault,
FormField.save_object_data(instance, name, value) should set instance attributes.
Called by save() before writting the database, when instance.pk may not be set, it overrides
ModelField.save_form_data() which is normally used in this occasion for non-m2m and non-
virtual model fields.
FormField.save_relation_data(instance, name, value) should save relations re-
quired for value on the instance. Called by save() after writting the database, when instance.pk is
necessarely set, it overrides ModelField.save_form_data() which is normally used in this occa-
sion for m2m and virtual model fields.
For complete rationale, see this modules docstring.
save(commit=True)
Backport from Django 1.9+ for 1.8.
Views
30 Chapter 6. API
django-autocomplete-light Documentation, Release 3.2.9
get_results(context)
Return data for the results key of the response.
render_to_response(context)
Return a JSON response in Select2 format.
Widgets
Fields
Test tools
Fields
Model choice fields that take a ContentType too: for generic relations.
class dal_contenttypes.fields.ContentTypeModelFieldMixin
Common methods for form fields for GenericForeignKey.
ModelChoiceFieldMixin expects options to look like:
prepare_value(value)
Return a ctypeid-objpk string for value.
class dal_contenttypes.fields.ContentTypeModelMultipleFieldMixin
Same as ContentTypeModelFieldMixin, but supports value list.
prepare_value(value)
Run the parents method for each value.
32 Chapter 6. API
django-autocomplete-light Documentation, Release 3.2.9
class dal_contenttypes.fields.GenericModelMixin
GenericForeignKey support for form fields, with FutureModelForm.
GenericForeignKey enforce editable=false, this class implements save_object_data() and value_from_object()
to allow FutureModelForm to compensate.
save_object_data(instance, name, value)
Set the attribute, for FutureModelForm.
value_from_object(instance, name)
Get the attribute, for FutureModelForm.
Views
url(
'^your-generic-autocomplete/$',
autocomplete.Select2QuerySetSequenceView.as_view(
queryset=autocomplete.QuerySetSequence(
Group.objects.all(),
TestModel.objects.all(),
)
),
name='your-generic-autocomplete',
)
It is compatible with the widgets and the fields of dal_contenttypes, suits generic relation autocom-
pletes.
get_results(context)
Return a list of results usable by Select2.
It will render as a list of one <optgroup> per different content type containing a list of one <option> per
model.
Wigets
class dal_select2_queryset_sequence.widgets.QuerySetSequenceSelect2(url=None,
for-
ward=None,
*args,
**kwargs)
Single model select for a generic select2 autocomplete.
class dal_select2_queryset_sequence.widgets.QuerySetSequenceSelect2Multiple(url=None,
for-
ward=None,
*args,
**kwargs)
Multiple model select for a generic select2 autocomplete.
Views
Fields
34 Chapter 6. API
django-autocomplete-light Documentation, Release 3.2.9
raise_invalid_choice(params=None)
Raise a ValidationError for invalid_choice.
The validation error left unprecise about the exact error for security reasons, to prevent an attacker doing
information gathering to reverse valid content type and object ids.
class dal_queryset_sequence.fields.QuerySetSequenceModelField(queryset,
empty_label=u
, required=True,
widget=None,
label=None,
initial=None,
help_text=u,
to_field_name=None,
limit_choices_to=None,
*args, **kwargs)
Replacement for ModelChoiceField supporting QuerySetSequence choices.
to_python(value)
Given a string like 3-5, return the model of ctype #3 and pk 5.
Note that in the case of ModelChoiceField, to_python is also in charge of security, its important to get the
results from self.queryset.
class dal_queryset_sequence.fields.QuerySetSequenceModelMultipleField(queryset,
re-
quired=True,
wid-
get=None,
la-
bel=None,
ini-
tial=None,
help_text=u,
*args,
**kwargs)
ModelMultipleChoiceField with support for QuerySetSequence choices.
Widgets
class dal_queryset_sequence.widgets.QuerySetSequenceSelectMultiple(url=None,
for-
ward=None,
*args,
**kwargs)
SelectMultiple widget for QuerySetSequence choices.
dal_gm2m_queryset_sequence
Fields
dal_genericm2m_queryset_sequence
Fields
Fields
36 Chapter 6. API
django-autocomplete-light Documentation, Release 3.2.9
class dal_gm2m.fields.GM2MFieldMixin
GM2MField ror FutureModelForm.
save_relation_data(instance, name, value)
Save the relation into the GM2MField.
value_from_object(instance, name)
Return the list of objects in the GM2MField relation.
Fields
Fields
Fields
38 Chapter 6. API
CHAPTER 7
genindex
modindex
search
39
django-autocomplete-light Documentation, Release 3.2.9
d
dal.forms, 29
dal.views, 27
dal.widgets, 28
dal_contenttypes.fields, 32
dal_genericm2m.fields, 37
dal_genericm2m_queryset_sequence.fields,
36
dal_gm2m.fields, 36
dal_gm2m_queryset_sequence.fields, 36
dal_queryset_sequence.fields, 34
dal_queryset_sequence.views, 34
dal_queryset_sequence.widgets, 35
dal_select2.fields, 31
dal_select2.test, 32
dal_select2.views, 30
dal_select2.widgets, 31
dal_select2_queryset_sequence.views, 33
dal_select2_queryset_sequence.widgets,
33
dal_select2_tagging.widgets, 37
dal_select2_taggit.widgets, 37
41
django-autocomplete-light Documentation, Release 3.2.9
A dal_select2_tagging.widgets (module), 37
autocomplete_function (dal.widgets.WidgetMixin at- dal_select2_taggit.widgets (module), 37
tribute), 28 dispatch() (dal.views.ViewMixin method), 28
B F
BaseQuerySetSequenceView (class in filter_choices_to_render()
dal_queryset_sequence.views), 34 (dal.widgets.QuerySetSelectMixin method), 28
BaseQuerySetView (class in dal.views), 27 filter_choices_to_render() (dal.widgets.WidgetMixin
build_attrs() (dal.widgets.WidgetMixin method), 28 method), 28
build_attrs() (dal_select2.widgets.TagSelect2 method), 31 filter_choices_to_render()
(dal_queryset_sequence.widgets.QuerySetSequenceSelectMixin
C method), 35
format_value() (dal_select2.widgets.TagSelect2 method),
clean_label() (dal_select2.test.Select2Story method), 32
31
ContentTypeModelFieldMixin (class in
forward (dal.widgets.WidgetMixin attribute), 28
dal_contenttypes.fields), 32
forwarded (dal.views.ViewMixin attribute), 28
ContentTypeModelMultipleFieldMixin (class in
FutureModelForm (class in dal.forms), 30
dal_contenttypes.fields), 32
create_field (dal.views.BaseQuerySetView attribute), 27
create_object() (dal.views.BaseQuerySetView method),
G
27 GenericM2MFieldMixin (class in
dal_genericm2m.fields), 37
D GenericM2MQuerySetSequenceField (class in
dal.forms (module), 29 dal_genericm2m_queryset_sequence.fields),
dal.views (module), 27 36
dal.widgets (module), 28 GenericModelMixin (class in dal_contenttypes.fields), 32
dal_contenttypes.fields (module), 32 get() (dal_select2.views.Select2ListView method), 30
dal_genericm2m.fields (module), 37 get_content_type_id_object_id()
dal_genericm2m_queryset_sequence.fields (module), 36 (dal_queryset_sequence.fields.QuerySetSequenceFieldMixin
dal_gm2m.fields (module), 36 method), 34
dal_gm2m_queryset_sequence.fields (module), 36 get_create_option() (dal_select2.views.Select2ViewMixin
dal_queryset_sequence.fields (module), 34 method), 30
dal_queryset_sequence.views (module), 34 get_list() (dal_select2.views.Select2ListView method),
dal_queryset_sequence.widgets (module), 35 30
dal_select2.fields (module), 31 get_model_name() (dal_queryset_sequence.views.BaseQuerySetSequenceV
dal_select2.test (module), 32 method), 34
dal_select2.views (module), 30 get_paginate_by() (dal_queryset_sequence.views.BaseQuerySetSequenceVi
dal_select2.widgets (module), 31 method), 34
dal_select2_queryset_sequence.views (module), 33 get_queryset() (dal.views.BaseQuerySetView method),
dal_select2_queryset_sequence.widgets (module), 33 27
43
django-autocomplete-light Documentation, Release 3.2.9
get_queryset() (dal_queryset_sequence.views.BaseQuerySetSequenceView
QuerySetSelectMixin (class in dal.widgets), 28
method), 34 QuerySetSequenceFieldMixin (class in
get_queryset_for_content_type() dal_queryset_sequence.fields), 34
(dal_queryset_sequence.fields.QuerySetSequenceFieldMixin
QuerySetSequenceModelField (class in
method), 34 dal_queryset_sequence.fields), 35
get_result_label() (dal.views.BaseQuerySetView QuerySetSequenceModelMultipleField (class in
method), 27 dal_queryset_sequence.fields), 35
get_result_value() (dal.views.BaseQuerySetView QuerySetSequenceSelect (class in
method), 27 dal_queryset_sequence.widgets), 35
get_result_value() (dal_queryset_sequence.views.BaseQuerySetSequenceView
QuerySetSequenceSelect2 (class in
method), 34 dal_select2_queryset_sequence.widgets),
get_results() (dal_select2.views.Select2ViewMixin 33
method), 30 QuerySetSequenceSelect2Multiple (class in
get_results() (dal_select2_queryset_sequence.views.Select2QuerySetSequenceView
dal_select2_queryset_sequence.widgets),
method), 33 34
GM2MFieldMixin (class in dal_gm2m.fields), 36 QuerySetSequenceSelectMixin (class in
GM2MQuerySetSequenceField (class in dal_queryset_sequence.widgets), 35
dal_gm2m_queryset_sequence.fields), 36 QuerySetSequenceSelectMultiple (class in
dal_queryset_sequence.widgets), 35
H
has_add_permission() (dal.views.BaseQuerySetView R
method), 27 raise_invalid_choice() (dal_queryset_sequence.fields.QuerySetSequenceFie
has_more() (dal.views.BaseQuerySetView method), 27 method), 34
has_more() (dal_queryset_sequence.views.BaseQuerySetSequenceView
render() (dal.widgets.WidgetMixin method), 29
method), 34 render_forward_conf() (dal.widgets.WidgetMixin
method), 29
L render_options() (dal.widgets.WidgetMixin method), 29
ListSelect2 (class in dal_select2.widgets), 31 render_options() (dal_select2_tagging.widgets.TaggingSelect2
method), 38
M render_options() (dal_select2_taggit.widgets.TaggitSelect2
mixup_querysets() (dal_queryset_sequence.views.BaseQuerySetSequenceView
method), 37
method), 34 render_to_response() (dal_select2.views.Select2ViewMixin
ModelSelect2 (class in dal_select2.widgets), 31 method), 31
ModelSelect2Multiple (class in dal_select2.widgets), 31
S
O save() (dal.forms.FutureModelForm method), 30
optgroups() (dal.widgets.WidgetMixin method), 29 save_object_data() (dal_contenttypes.fields.GenericModelMixin
optgroups() (dal_select2.widgets.TagSelect2 method), 31 method), 33
option_value() (dal_select2.widgets.TagSelect2 method), save_relation_data() (dal_genericm2m.fields.GenericM2MFieldMixin
31 method), 37
option_value() (dal_select2_taggit.widgets.TaggitSelect2 save_relation_data() (dal_gm2m.fields.GM2MFieldMixin
method), 37 method), 37
options() (dal_select2.widgets.TagSelect2 method), 31 Select (class in dal.widgets), 28
Select2 (class in dal_select2.widgets), 31
P Select2ListChoiceField (class in dal_select2.fields), 31
post() (dal.views.BaseQuerySetView method), 27 Select2ListCreateChoiceField (class in
post() (dal_select2.views.Select2ListView method), 30 dal_select2.fields), 32
prepare_value() (dal_contenttypes.fields.ContentTypeModelFieldMixin
Select2ListView (class in dal_select2.views), 30
method), 32 Select2Multiple (class in dal_select2.widgets), 31
prepare_value() (dal_contenttypes.fields.ContentTypeModelMultipleFieldMixin
Select2QuerySetSequenceView (class in
method), 32 dal_select2_queryset_sequence.views), 33
Select2QuerySetView (class in dal_select2.views), 30
Q Select2Story (class in dal_select2.test), 32
q (dal.views.ViewMixin attribute), 28 Select2ViewMixin (class in dal_select2.views), 30
44 Index
django-autocomplete-light Documentation, Release 3.2.9
T
TaggingSelect2 (class in dal_select2_tagging.widgets), 37
TaggitSelect2 (class in dal_select2_taggit.widgets), 37
TagSelect2 (class in dal_select2.widgets), 31
to_python() (dal_queryset_sequence.fields.QuerySetSequenceModelField
method), 35
U
url (dal.widgets.WidgetMixin attribute), 28
V
validate() (dal_select2.fields.Select2ListCreateChoiceField
method), 32
value_from_datadict() (dal_select2.widgets.TagSelect2
method), 31
value_from_datadict() (dal_select2_taggit.widgets.TaggitSelect2
method), 37
value_from_object() (dal_contenttypes.fields.GenericModelMixin
method), 33
value_from_object() (dal_genericm2m.fields.GenericM2MFieldMixin
method), 37
value_from_object() (dal_gm2m.fields.GM2MFieldMixin
method), 37
ViewMixin (class in dal.views), 27
W
wait_script() (dal_select2.test.Select2Story method), 32
WidgetMixin (class in dal.widgets), 28
Index 45
Django-autocomplete-light supports handling generic many-to-many relations using GM2MField by providing specialized widgets such as QuerySetSequenceSelect2Multiple that can handle multiple models. This field leverages the power of Select2 for rendering distinct elements in a cohesive manner and also supports FutureModelForm to manage non-editable fields like GM2MField, ensuring that the form only renders selected choices at initialization to conserve resources and enhance performance .
Using QuerySetSequence with Select2 provides advantages such as combining querysets from different models into a single autocomplete functionality. This is particularly useful for applications requiring autocompletions across multiple models, allowing complex data retrieval in a user-friendly manner. QuerySetSequence enables filtering across different datasets while maintaining uniform results, and Select2 presents this data with a dynamic and responsive user interface, offering seamless interaction for the users .
FutureModelForm requires custom methods like save_object_data and save_relation_data to be defined in the form field to accommodate specific save operations. These methods allow for distinct handling of object attributes and relations, diverging from the typical save_form_data approach that is called twice during the save process in standard forms. By implementing save_object_data and save_relation_data, developers can customize how instance attributes are set and relations are saved post-cleaning, thus offering more control over data persistence and validation workflows in non-standard or complex forms .
To use Select2 in a Django ModelAdmin form with django-autocomplete-light, one needs to override the form associated with the ModelAdmin. This involves importing the custom form featuring a ModelSelect2 widget linked to an autocomplete URL, and then assigning this form to the ModelAdmin's form attribute. Additionally, registration of the view to handle the autocomplete requests and ensuring the necessary JavaScript libraries are loaded in the Django admin templates are necessary steps to complete the integration .
Exposing data through public URLs in django-autocomplete-light poses security risks such as unauthorized data access. To mitigate these concerns, it is critical to implement proper permission checks within the get_queryset method to ensure only authenticated users can view the data. This involves verifying the user's authentication status and applying relevant filters to the queryset based on user permissions .
The Select2ListCreateChoiceField in django-autocomplete-light allows for the specification of custom text choices by using a Select2List widget and defining a create method to handle these values. The get_list method can return a list of textual choices and opt-groups if needed, allowing views to provide bespoke selection lists without relying on a static choice set. This approach simplifies the management of dynamic choice fields, especially when integrating forms that need to process and validate user-generated text .
Widgets from the dal_select2_taggit module can be utilized in Django applications to manage tag-based inputs by providing specialized interfaces that handle multi-word tags seamlessly, adhering to taggit's handling of tag data. These widgets, such as TaggitSelect2, automatically manage the rendering of selected tags and support dynamic additions through a comfortable user interface. They ensure inputs are properly formatted for both tag display and backend data processing, enhancing user interaction and data integrity in tag-based fields .
Select2ViewMixin enhances autocompletion capabilities by providing a structured way to render JSON responses necessary for Select2 interfaces, thereby transforming HTTP responses into formats directly consumable by Select2 frontend components. It includes methods like get_results to filter results dynamically and get_create_option to define what happens when a user enters new text, ensuring the interface remains interactive and intuitive .
The QuerySetSequenceSelect2 widget is used for single selections in a Select2 widget environment. It provides autocomplete functionality by integrating multiple querysets, allowing users to select one item from a streamline of available options across different datasets. Conversely, the QuerySetSequenceSelect2Multiple supports multiple selections, enabling users to choose multiple items simultaneously. This widget is particularly beneficial in scenarios where a model contains relations to multiple models, requiring complex selections to be managed efficiently .
The django-autocomplete-light package integrates Select2 with Django by allowing the creation of custom autocomplete views and widgets for ForeignKey fields. It utilizes the ModelSelect2 widget to enable this functionality by linking a ModelChoiceField to an autocomplete URL. This URL is associated with a specific autocomplete view that filters data returned based on user input, enabling autocomplete suggestions in real-time. The package also supports additional configurations such as minimum input length and data placeholders to enhance user experience .