Python API#


Base views for autocomplete widgets.

class dal.views.BaseQuerySetView(**kwargs)[source]#

Base view to get results from a QuerySet.


Name of the field to use to create missing values. For example, if create_field=’title’, and the user types in “foo”, then the autocomplete view will propose an option ‘Create “foo”’ if it can’t find any value matching “foo”. When the user does click ‘Create “foo”’, the autocomplete script should POST to this view to create the object and get back the newly created object id.


Name of the Model field to run filter against.


Create an object given a text.


Filter the queryset with GET[‘q’].


Return the label of a result.


Return the value of a result.


Get the fields to search over.

get_search_results(queryset, search_term)[source]#

Filter the results based on the query.


Return the label of a selected result.


Return True if the user has the permission to add a model.


For widgets that have infinite-scroll feature.

lookup_needs_distinct(queryset, orm_lookups)[source]#

Return True if an orm_lookup requires calling qs.distinct().

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

Create an object given a text after checking permissions.

Runs self.validate() if self.validate_create is True.


Validate a given text for new option creation.

Raise ValidationError or return None.

class dal.views.ViewMixin[source]#

Common methods for autocomplete views.

It is assumed this view will be used in conjunction with a Django View based class that will implement OPTIONS.


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.


Query string as typed by the user in the autocomplete field.

dispatch(request, *args, **kwargs)[source]#

Set forwarded and q.


Autocomplete widgets bases.

class dal.widgets.QuerySetSelectMixin(url=None, forward=None, *args, **kwargs)[source]#

QuerySet support for choices.


Filter out un-selected choices if choices is a QuerySet.

class dal.widgets.Select(url=None, forward=None, *args, **kwargs)[source]#

Replacement for Django’s Select to render only selected choices.

class dal.widgets.SelectMultiple(url=None, forward=None, *args, **kwargs)[source]#

Replacement SelectMultiple to render only selected choices.

class dal.widgets.WidgetMixin(url=None, forward=None, *args, **kwargs)[source]#

Base mixin for autocomplete widgets.


Absolute URL to the autocomplete view for the widget. It can be set to a URL name, in which case it will be reversed when the attribute is accessed.


List of field names to forward to the autocomplete view, useful to filter results using values of other fields in the form.

Items of the list must be one of the following:
  • string (e. g. “some_field”): forward a value from the field with named “some_field”;

  • dal.forward.Field("some_field"): the same as above;

  • dal.forward.Field("some_field", "dst_field"): forward a value from the field with named “some_field” as “dst_field”;

  • dal.forward.Const("some_value", "dst_field"): forward a constant value “some_value” as “dst_field”.


Identifier of the javascript callback that should be executed when such a widget is loaded in the DOM, either on page load or dynamically.

build_attrs(*args, **kwargs)[source]#

Build HTML attributes for the widget.


Replace self.choices with selected_choices.

optgroups(name, value, attrs=None)[source]#

Exclude unselected self.choices before calling the parent method.

Used by Django>=1.10.

render(name, value, attrs=None, renderer=None, **kwargs)[source]#

Call Django render together with render_forward_conf.


Render forward configuration for the field.


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.


tl;dr: See FutureModelForm’s docstring.

Many apps provide new related managers to extend your django models with. For example, django-tagulous provides a TagField which abstracts an M2M relation with the Tag model, django-gm2m provides a GM2MField which abstracts an relation, django-taggit provides a TaggableManager which abstracts a relation too, django-generic-m2m provides RelatedObjectsDescriptor which abstracts a relation again.

While that works pretty well, it gets a bit complicated when it comes to encapsulating the business logic for saving such data in a form object. This is three-part problem:

  • getting initial data,

  • saving instance attributes,

  • saving relations like reverse relations or many to many.

Django’s ModelForm calls the model field’s value_from_object() method to get the initial data. FutureModelForm tries the value_from_object() method from the form field instead, if defined. Unlike the model field, the form field doesn’t know its name, so FutureModelForm passes it when calling the form field’s value_from_object() method.

Django’s ModelForm calls the form field’s save_form_data() in two occasions:

  • in _post_clean() for model fields in Meta.fields,

  • in _save_m2m() for model fields in Meta.virtual_fields and Meta.many_to_many, which then operate on an instance which as a PK.

If we just added save_form_data() to form fields like for value_from_object() then it would be called twice, once in _post_clean() and once in _save_m2m(). Instead, FutureModelForm would call the following methods from the form field, if defined:

  • save_object_data() in _post_clean(), to set object attributes for a given value,

  • save_relation_data() in _save_m2m(), to save relations for a given value.

For example:

  • 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)[source]#

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 default,

  • FormField.save_object_data(instance, name, value) should set instance attributes. Called by save() before writing the database, when 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 required for value on the instance. Called by save() after writing the database, when is necessarily set, it overrides ModelField.save_form_data() which is normally used in this occasion for m2m and virtual model fields.

For complete rationale, see this module’s docstring.

classmethod as_urls()[source]#

Create a list of url patterns, to be called in



Iterate over the fields to call the as_url() method from the GenericForeignKeyField

property media#

Return all media required to render the widgets on this form.


Backport from Django 1.9+ for 1.8.


This is a front-end module: it provides views and widgets.


Select2 view implementation.

class dal_select2.views.Select2GroupListView(**kwargs)[source]#

View mixin for grouped options.

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

Return option list with children(s) json response.


Return the item with its group.

class dal_select2.views.Select2GroupQuerySetView(**kwargs)[source]#

List of grouped options for a Select2 widget.

Name of the field for the related Model on a One to Many relation


Name of the related Model field to run filter against.


Return the options grouped by a common related model.

Raises ImproperlyConfigured if self.group_by_name is not configured

class dal_select2.views.Select2ListView(**kwargs)[source]#

Autocomplete from a list of items rather than a QuerySet.


Return list of strings that match the autocomplete query.

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

Return option list json response.


Return the list strings from which to autocomplete.

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

Add an option to the autocomplete list.

If ‘text’ is not defined in POST or self.create(text) fails, raises bad request. Raises ImproperlyConfigured if self.create if not defined.


Return the result dictionary.

class dal_select2.views.Select2QuerySetView(**kwargs)[source]#

List options for a Select2 widget.

class dal_select2.views.Select2ViewMixin[source]#

View mixin to render a JSON response for Select2.

get_create_option(context, q)[source]#

Form the correct create_option to append to results.


Return data for the ‘results’ key of the response.


Return a JSON response in Select2 format.


Select2 widget implementation module.

class dal_select2.widgets.ListSelect2(url=None, forward=None, *args, **kwargs)[source]#

Select widget for regular choices and Select2.

property media#

Return JS/CSS resources for the widget.

class dal_select2.widgets.ModelSelect2(url=None, forward=None, *args, **kwargs)[source]#

Select widget for QuerySet choices and Select2.

property media#

Return JS/CSS resources for the widget.

class dal_select2.widgets.ModelSelect2Multiple(url=None, forward=None, *args, **kwargs)[source]#

SelectMultiple widget for QuerySet choices and Select2.

property media#

Return JS/CSS resources for the widget.

class dal_select2.widgets.Select2(url=None, forward=None, *args, **kwargs)[source]#

Select2 widget for regular choices.

property media#

Return JS/CSS resources for the widget.

class dal_select2.widgets.Select2Multiple(url=None, forward=None, *args, **kwargs)[source]#

Select2Multiple widget for regular choices.

property media#

Return JS/CSS resources for the widget.

class dal_select2.widgets.Select2WidgetMixin[source]#

Mixin for Select2 widgets.

build_attrs(*args, **kwargs)[source]#

Set data-autocomplete-light-language.

property media#

Return JS/CSS resources for the widget.

class dal_select2.widgets.TagSelect2(url=None, forward=None, *args, **kwargs)[source]#

Select2 in tag mode.

build_attrs(*args, **kwargs)[source]#

Automatically set data-tags=1.


Return the list of HTML option values for a form field value.

property media#

Return JS/CSS resources for the widget.

optgroups(name, value, attrs=None)[source]#

Return a list of one optgroup and selected values.


Return the HTML option value attribute for a value.

options(name, value, attrs=None)[source]#

Return only select options.

value_from_datadict(data, files, name)[source]#

Return a comma-separated list of options.

This is needed because Select2 uses a multiple select even in tag mode, and the model field expects a comma-separated list of tags.


Ensure lang_code is supported by Select2.


Select2 field implementation module.

class dal_select2.fields.ChoiceCallable(choices)[source]#

Choices wrapper that supports callable choices.

class dal_select2.fields.Select2ListChoiceField(choice_list=None, required=True, widget=None, label=None, initial=None, help_text='', *args, **kwargs)[source]#

Allows a list of values to be used with a ChoiceField.

Avoids unusual things that can happen if Select2ListView is used for a form where the text and value for choices are not the same.

class dal_select2.fields.Select2ListCreateChoiceField(choice_list=None, required=True, widget=None, label=None, initial=None, help_text='', *args, **kwargs)[source]#

Skips validation of choices so any value can be used.


Do not validate choices but check for empty.

Test tools#

Helpers for DAL user story based tests.

class dal_select2.test.Select2Story[source]#

Define Select2 CSS selectors.


Remove the “remove” character used in select2.


Wait for scripts to be loaded and ready to work.



Model choice fields that take a ContentType too: for generic relations.

class dal_contenttypes.fields.ContentTypeModelFieldMixin[source]#

Common methods for form fields for GenericForeignKey.

ModelChoiceFieldMixin expects options to look like:

<option value="4">Model #4</option>

With a ContentType of id 3 for that model, it becomes:

<option value="3-4">Model #4</option>

Return a ctypeid-objpk string for value.

class dal_contenttypes.fields.ContentTypeModelMultipleFieldMixin[source]#

Same as ContentTypeModelFieldMixin, but supports value list.


Run the parent’s method for each value.

class dal_contenttypes.fields.GenericModelMixin[source]#

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)[source]#

Set the attribute, for FutureModelForm.

value_from_object(instance, name)[source]#

Get the attribute, for FutureModelForm.



View for a Select2 widget and QuerySetSequence-based business logic.

class dal_select2_queryset_sequence.views.Select2QuerySetSequenceAutoView(**kwargs)[source]#

Select2QuerySetSequenceAutoView class.

Filter the queryset based on the models and filter attributes of the GenericForeignKeyModelField

self.model_choice is generated from the Select2GenericForeignKeyModelField, see it’s docstring


Return queryset.

class dal_select2_queryset_sequence.views.Select2QuerySetSequenceView(**kwargs)[source]#

Combines support QuerySetSequence and Select2 in a single view.

Example usage:


It is compatible with the widgets and the fields of fields, suits generic relation autocompletes.


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.


Autocomplete fields for Select2GenericForeignKey choices.

class dal_select2_queryset_sequence.fields.Select2GenericForeignKeyModelField(*args, **kwargs)[source]#

Select2GenericForeignKeyModelField class.

Field that generate automatically the view for the QuerySetSequenceSelect2 widget


Return url.


Widgets for Select2 and QuerySetSequence.

They combine Select2WidgetMixin and QuerySetSequenceSelectMixin with Django’s Select and SelectMultiple widgets, and are meant to be used with generic model form fields such as those in dal_contenttypes.fields.

class dal_select2_queryset_sequence.widgets.QuerySetSequenceSelect2(url=None, forward=None, *args, **kwargs)[source]#

Single model select for a generic select2 autocomplete.

property media#

Return JS/CSS resources for the widget.

class dal_select2_queryset_sequence.widgets.QuerySetSequenceSelect2Multiple(url=None, forward=None, *args, **kwargs)[source]#

Multiple model select for a generic select2 autocomplete.

property media#

Return JS/CSS resources for the widget.



View that supports QuerySetSequence.

class dal_queryset_sequence.views.BaseQuerySetSequenceView(**kwargs)[source]#

Base view that uses a QuerySetSequence.

Compatible with form fields which use a ContentType id as well as a model pk to identify a value.


Cause the autocomplete to show a few results of each querysets.


Return the name of the model, fetch parent if model is a proxy.


Don’t paginate if mixup.


Mix results from all querysets in QuerySetSequence if self.mixup.


Return ctypeid-objectid for result.


Return False if mixup.

lookup_needs_distinct(queryset, orm_lookups)[source]#

Return True if a orm_lookups requires calling qs.distinct().


Return a queryset with different model types.


Autocomplete fields for QuerySetSequence choices.

class dal_queryset_sequence.fields.GenericForeignKeyModelField(*args, **kwargs)[source]#

Field that generate automatically the view for compatible widgets.


Return url.

class dal_queryset_sequence.fields.QuerySetSequenceFieldMixin[source]#

Base methods for QuerySetSequence fields.


Return a tuple of ctype id, object id for value.


Return the QuerySet from the QuerySetSequence for a ctype.


Raise a ValidationError for invalid_choice.

The validation error left imprecise 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='---------', required=True, widget=None, label=None, initial=None, help_text='', to_field_name=None, limit_choices_to=None, blank=False, **kwargs)[source]#

Replacement for ModelChoiceField supporting QuerySetSequence choices.


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, it’s important to get the results from self.queryset.

class dal_queryset_sequence.fields.QuerySetSequenceModelMultipleField(queryset, **kwargs)[source]#

ModelMultipleChoiceField with support for QuerySetSequence choices.


Widget mixin that only renders selected options with QuerySetSequence.

For details about why this is required, see dal.widgets.

class dal_queryset_sequence.widgets.QuerySetSequenceSelect(url=None, forward=None, *args, **kwargs)[source]#

Select widget for QuerySetSequence choices.

class dal_queryset_sequence.widgets.QuerySetSequenceSelectMixin(url=None, forward=None, *args, **kwargs)[source]#

Support QuerySetSequence in WidgetMixin.


Overwrite self.choices to exclude unselected values.


Convert an object into string. Override it to customize display.

class dal_queryset_sequence.widgets.QuerySetSequenceSelectMultiple(url=None, forward=None, *args, **kwargs)[source]#

SelectMultiple widget for QuerySetSequence choices.



Form fields for using django-gm2m with QuerySetSequence.

class dal_gm2m_queryset_sequence.fields.GM2MQuerySetSequenceField(queryset, **kwargs)[source]#

Form field for QuerySetSequence to django-generic-m2m relation.



Autocomplete fields for django-queryset-sequence and django-generic-m2m.

class dal_genericm2m_queryset_sequence.fields.GenericM2MQuerySetSequenceField(queryset, **kwargs)[source]#

Autocomplete field for GM2MField() for QuerySetSequence choices.



GM2MField support for autocomplete fields.

class dal_gm2m.fields.GM2MFieldMixin[source]#

GM2MField ror FutureModelForm.

save_relation_data(instance, name, value)[source]#

Save the relation into the GM2MField.

value_from_object(instance, name)[source]#

Return the list of objects in the GM2MField relation.



django-generic-m2m field mixin for FutureModelForm.

class dal_genericm2m.fields.GenericM2MFieldMixin[source]#

Form field mixin able to get / set instance generic-m2m relations.

save_relation_data(instance, name, value)[source]#

Update the relation to be value.

value_from_object(instance, name)[source]#

Return the list of related objects.



Widgets for Select2 and django-taggit.

class dal_select2_taggit.widgets.TaggitSelect2(url=None, forward=None, *args, **kwargs)[source]#

Select2 tag widget for taggit’s TagField.

build_attrs(*args, **kwargs)[source]#

Add data-tags=”,”.

property media#

Return JS/CSS resources for the widget.


Return attribute of value.


Render only selected tags.

Remove when Django < 1.10 support is dropped.

value_from_datadict(data, files, name)[source]#

Handle multi-word tag.

Insure there’s a comma when there’s only a single multi-word tag, or tag “Multi word” would end up as “Multi” and “word”.



Widgets for Select2 and django-taggit.

class dal_select2_tagging.widgets.TaggingSelect2(url=None, forward=None, *args, **kwargs)[source]#

Select2 tag widget for tagging’s TagField.

property media#

Return JS/CSS resources for the widget.


Render only selected tags.