Python API¶
Views¶
Base views for autocomplete widgets.
- class dal.views.BaseQuerySetView(**kwargs)[source]¶
Base view to get results from a QuerySet.
- create_field¶
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.
- model_field_name¶
Name of the Model field to run filter against.
- class dal.views.ViewMixin[source]¶
Common methods for autocomplete views.
It is assumed this view will be used in conjunction with a Django
Viewbased class 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_dataexample for reference.
- q¶
Query string as typed by the user in the autocomplete field.
Widgets¶
Autocomplete widgets bases.
- class dal.widgets.QuerySetSelectMixin(url=None, forward=None, *args, **kwargs)[source]¶
QuerySet support for choices.
- 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.
- url¶
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.
- forward¶
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”.
- autocomplete_function¶
Identifier of the javascript callback that should be executed when such a widget is loaded in the DOM, either on page load or dynamically.
- filter_choices_to_render(selected_choices)[source]¶
Filter choices to selected ones; inject values absent from the list.
- optgroups(name, value, attrs=None)[source]¶
Exclude unselected self.choices before calling the parent method.
Used by Django>=1.10.
Forward¶
Classes for class-based forward declaration.
- class dal.forward.Const(val, dst)[source]¶
Forward arbitrary constant value.
- val¶
The value to forward. Must be JSON-serializable.
- dst¶
The name of the key of the forwarded value.
- class dal.forward.Field(src, dst=None)[source]¶
Forward field value.
The type of the forwarded value from the field is either string, list of strings or boolean.
The following rules are used to deduce the forwarded type.
If there is only one field in the form or subform with name
srcand this field is a checkbox withoutvalueHTML-attribute, then boolean value indicating if this checkbox is checked is forwarded.If there is only one field in the form or subform with name
srcand it hasmultipleHTML-attribute, then this field is forwarded as a list of strings, containing values from this field.If there are one or more fields in the form with name
srcand all of them are checkboxes with HTML-attributevalueset the list of strings containing checked checkboxes is forwarded.Otherwise
srcfield value forwarded as a string.
- src¶
The name of the form field whose value will be forwarded to a view.
- dst¶
The name of the key of the forwarded value from the src field in the forwarded dictionary. If this value is
None, then the key issrc.
- class dal.forward.Forward[source]¶
Base class for autocomplete forward declaration.
- property type¶
Forward type. Should be implemented in subclasses.
- class dal.forward.JavaScript(handler, dst=None)[source]¶
Run registered javascript handler and forward its returned value.
You can register custom forward handler in your JS code as follows:
yl.registerForwardHandler("your_handler", function (autocompleteElement) { // your code here });
Then if your add
JavaScript("your_handler", "some_value")to your forwards declaration, your function will be called, autocomplete field HTML element will be passed asautocompleteElementand returned value will be added to forward dictionary withsome_valuekey.- handler¶
The name of the registered handler.
- dst¶
The name of the key of the forwarded value from the src field in the forwarded dictionary. If this value is
None, then the key ishandler.
FutureModelForm¶
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 inMeta.fields,in
_save_m2m()for model fields inMeta.virtual_fieldsandMeta.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, overridesModelField.value_from_object()which is what ModelForm uses by default,FormField.save_object_data(instance, name, value)should set instance attributes. Called bysave()before writing the database, wheninstance.pkmay not be set, it overridesModelField.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 bysave()after writing the database, wheninstance.pkis necessarily set, it overridesModelField.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 url.py.
Example:
urlpattern.append(*ModelForm.as_url())
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.
dal_select2¶
This is a front-end module: it provides views and widgets.
Views¶
Select2 view implementation.
- 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.
- class dal_select2.views.Select2ListView(**kwargs)[source]¶
Autocomplete from a list of items rather than a QuerySet.
Widgets¶
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.
- filter_choices_to_render(selected_choices)[source]¶
Filter choices preserving the order submitted by 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.
- property media¶
Return JS/CSS resources for the widget.
Fields¶
Test tools¶
Helpers for DAL user story based tests.
dal_contenttypes¶
Fields¶
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>
- class dal_contenttypes.fields.ContentTypeModelMultipleFieldMixin[source]¶
Same as ContentTypeModelFieldMixin, but supports value list.
dal_select2_queryset_sequence¶
Views¶
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
- class dal_select2_queryset_sequence.views.Select2QuerySetSequenceView(**kwargs)[source]¶
Combines support QuerySetSequence and Select2 in a single view.
Example usage:
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
widgetsand the fields offields, suits generic relation autocompletes.
Fields¶
Autocomplete fields for Select2GenericForeignKey choices.
Wigets¶
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.
dal_queryset_sequence¶
Views¶
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.
- mixup¶
Cause the autocomplete to show a few results of each querysets.
Fields¶
Autocomplete fields for QuerySetSequence choices.
- class dal_queryset_sequence.fields.GenericForeignKeyModelField(*args, **kwargs)[source]¶
Field that generate automatically the view for compatible widgets.
- class dal_queryset_sequence.fields.QuerySetSequenceFieldMixin[source]¶
Base methods for QuerySetSequence fields.
- 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.
Widgets¶
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.
dal_select2_taggit¶
Fields¶
Widgets for Select2 and django-taggit.
dal_alight¶
Views¶
- class dal_alight.views.AlightGroupListView(**kwargs)[source]¶
Grouped list view — mirrors Select2GroupListView.
get_list()should return items of the form((group_id, group_label), [(value, label), …])or plain strings grouped by a leading group item.Simpler usage: return
[(group, item), …]tuples where the first element is the group name and the second is the item string or(value, label)tuple. Items withgroup=Noneare ungrouped.
- class dal_alight.views.AlightGroupQuerySetView(**kwargs)[source]¶
Grouped queryset view — mirrors Select2GroupQuerySetView.
Results are rendered as:
<div class="autocomplete-light-group">Group label</div> <div data-value="pk">Label</div> …
Group header divs carry no
data-valueso the component treats them as non-selectable.
- class dal_alight.views.AlightListView(**kwargs)[source]¶
Autocomplete from a list of strings or (value, label) pairs.
Mirrors
Select2ListViewbut returns HTML fragments instead of JSON.Override
get_list()to return your items. Each item may be a plain string (value == label) or a(value, label)tuple/list.Define
create(text)on the view to enable POST-based creation; it should return the created text/value or raise an error.
- class dal_alight.views.AlightQuerySetView(**kwargs)[source]¶
Autocomplete view returning HTML fragments for autocomplete-light.
Each result is rendered as
<div data-value="{pk}">{label}</div>. Whencreate_fieldis set and the query has no case-insensitive exact match on page 1, a<div data-create>Create "…"</div>is appended. POST is handled by the inheritedBaseQuerySetView.post()which creates the object and returns a<div data-value="…">…</div>HTML fragment.
Widgets¶
- class dal_alight.widgets.Alight(url=None, forward=None, *args, **kwargs)[source]¶
Single-select autocomplete for arbitrary choices.
Without a
urlthe component filters<option>elements locally in JS — no server round-trip needed. With aurlit fetches from the view as usual.
- class dal_alight.widgets.AlightMultiple(url=None, forward=None, *args, **kwargs)[source]¶
Multiple-select autocomplete for arbitrary choices.
- class dal_alight.widgets.AlightWidgetMixin[source]¶
Mixin that renders the autocomplete-light web component shell.
Wraps the underlying
<select>(rendered bysuper().render()) in:<autocomplete-select> <select slot="select">…</select> <div slot="deck"></div> <autocomplete-select-input slot="input" [url="…"]> <input …/> </autocomplete-select-input> <div class="dal-forward-conf">…</div> </autocomplete-select>
- class dal_alight.widgets.ListAlight(url=None, forward=None, *args, **kwargs)[source]¶
Single-select autocomplete backed by
AlightListView.Use alongside
AlightListViewon the server.
- class dal_alight.widgets.ModelAlight(url=None, forward=None, *args, **kwargs)[source]¶
Single-select autocomplete widget backed by a QuerySet.
- class dal_alight.widgets.ModelAlightMultiple(url=None, forward=None, *args, **kwargs)[source]¶
Multi-select autocomplete widget backed by a QuerySet.
- class dal_alight.widgets.TagAlight(url=None, forward=None, *args, **kwargs)[source]¶
Free-text tag widget — value stored as comma-separated text.
AlightInitialRenderMixin is intentionally omitted: tags are not PKs so the queryset-filter approach would break; optgroups() handles initial values directly via _iter_tag_values().
Tags are not backed by a model: the tag text IS the option value. Use alongside
AlightListViewwith acreate()method, or any view that returns HTML fragments.The stored field value is a comma-separated string (same as TagSelect2).
Fields¶
Test tools¶
Test helpers for dal_alight — mirrors dal_select2.test without select2.
- class dal_alight.test.AlightStory[source]¶
CSS selectors and wait logic for the autocomplete-light web component.
Drop-in replacement for
Select2Story. Mix intoAutocompleteTestCasesubclasses instead ofSelect2Story.HTML structure produced by
AlightWidgetMixin:<autocomplete-select> <select slot="select" id="id_{field}">…</select> <div slot="deck"> <div data-value="1">Label<span class="clear">×</span></div> </div> <autocomplete-select-input slot="input" url="…"> <input name="{field}-input" slot="input" class="vTextField" /> </autocomplete-select-input> </autocomplete-select>The dropdown box is appended to
<body>by the component:<div class="autocomplete-light-box"> <div data-value="1">Label</div> <div data-create data-value="foo">Create "foo"</div> </div>
- get_create_option_selector(name)[source]¶
Return a selector for the create option that matches
nameexactly.Using
[data-value="name"]prevents clicking a stale create option left over from a previous query before the new XHR has returned.
- toggle_autocomplete_widget(selector)[source]¶
Open the autocomplete, ensuring focus fires even if already focused.
For alight,
focuson the text input is what triggers the XHR. When the input already has focus (e.g. after a previous call inrefresh_autocomplete), a plain Selenium click does not re-firefocus. Blurring first resets the focus state so the subsequent click fires a realfocusevent and starts a fresh XHR.
- wait_script()[source]¶
Wait until all alight web components have finished connectedCallback.
autocomplete-select.connectedCallback fires before its child autocomplete-select-input’s callback (parent-first connection order), so it schedules a 100 ms retry. We must wait for BOTH elements to have data-bound before interacting: autocomplete-select installs the autocompleteChoiceSelected listener only on its own retry, and clicking an option before that listener exists silently does nothing.
dal_alight_queryset_sequence¶
Views¶
Views for autocomplete-light widget and QuerySetSequence-based business logic.
- class dal_alight_queryset_sequence.views.AlightQuerySetSequenceAutoView(**kwargs)[source]¶
AlightQuerySetSequenceAutoView class.
Filters the queryset based on the models and filter attributes defined on an
AlightGenericForeignKeyModelField.self.model_choiceis generated from that field; see its docstring for the expected structure.
- class dal_alight_queryset_sequence.views.AlightQuerySetSequenceView(**kwargs)[source]¶
Combines QuerySetSequence support with autocomplete-light HTML fragments.
Returns results grouped by model type, rendered as HTML divs instead of JSON. Group headers use
class="autocomplete-light-group"; individual results carry adata-valueattribute with thectype_pk-object_pkcomposite identifier used bydal_queryset_sequence.Example usage:
path( 'your-generic-autocomplete/', autocomplete.AlightQuerySetSequenceView.as_view( queryset=autocomplete.QuerySetSequence( Group.objects.all(), TestModel.objects.all(), ) ), name='your-generic-autocomplete', )
Compatible with
widgetsand the fields offieldsfor generic-relation autocompletes.
Widgets¶
Widgets for autocomplete-light and QuerySetSequence.
They combine AlightWidgetMixin 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.
Fields¶
Autocomplete fields for AlightGenericForeignKey choices.
- class dal_alight_queryset_sequence.fields.AlightGenericForeignKeyModelField(*args, **kwargs)[source]¶
AlightGenericForeignKeyModelField class.
Field that automatically generates the view for the
QuerySetSequenceAlightwidget.- Parameters:
model_choice –
[(Model, 'filter_by', [('forwardfield_name', 'filter_by')]), …]List of tuples, one per model to include in the autocomplete. Model is the Django model class;
'filter_by'is the field name used foricontainsfiltering. The optional third element is a list of(forwarded_field_name, model_field_name)pairs for forwarding form fields to the view.field_id – Optional stable identifier; defaults to
id(self).