### Install Django Autocomplete Light with Pip Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/install.md Use this command to install the latest stable version of the package from PyPI. ```bash pip install django-autocomplete-light ``` -------------------------------- ### Install Optional Dependencies for Django Autocomplete Light Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/install.md Install specific extras to enable support for GenericForeignKey, django-taggit, or django-nested-admin. ```bash pip install django-autocomplete-light[gfk] ``` ```bash pip install django-autocomplete-light[tags] ``` ```bash pip install django-autocomplete-light[nested] ``` -------------------------------- ### Install Django Autocomplete Light Dev Version with Git Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/install.md Install the development version directly from the GitHub repository for the latest features or bug fixes. ```bash pip install -e git+https://github.com/yourlabs/django-autocomplete-light.git#egg=django-autocomplete-light ``` -------------------------------- ### Set Up and Run the Demo Project Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/install.md Steps to install and configure the demo project in a temporary virtual environment for testing purposes. This includes setting up the database and creating a superuser. ```bash cd /tmp python3 -m venv dal_env source dal_env/bin/activate 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 ``` -------------------------------- ### Listen for Specific Input Initialization Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Listen for the `dal-element-initialized` event to perform actions on a specific Django Autocomplete Light input after it has been initialized. This example demonstrates opening a Select2 dropdown and setting focus on an input with a known ID. ```javascript $(document).on("dal-element-initialized", function (e) { if (e.detail.element.id === "my_dal_element_id") { $("#my_dal_element_id").select2("open").trigger("focus"); } }); ``` -------------------------------- ### Define Model with TaggableManager Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/taggit.md Example of a Django model using django-taggit's TaggableManager to add tag functionality. ```python from django.db import models from taggit.managers import TaggableManager class TestModel(models.Model): name = models.CharField(max_length=200) tags = TaggableManager() def __str__(self): return self.name ``` -------------------------------- ### Automatic Generic Foreign Key Form Field Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Use AlightGenericForeignKeyModelField for automatic setup of a Generic Foreign Key field in a form. Ensure necessary models like Country and City are defined. ```python from dal import autocomplete from django.contrib.auth.models import Group class TestForm(autocomplete.FutureModelForm): location = autocomplete.AlightGenericForeignKeyModelField( model_choice=[ (Country, 'name'), (City, 'name', [('language', 'spoken_language')]) ], ) class Meta: model = TestModel ``` -------------------------------- ### Automate Form Field Integration with djhacker Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Integrates autocomplete views and form fields automatically throughout Django without custom model forms. Requires `pip install djhacker`. ```python import djhacker from django import forms djhacker.formfield( Person.birth_country, forms.ModelChoiceField, widget=autocomplete.ModelSelect2(url='country-autocomplete') ) ``` -------------------------------- ### Customize Selected Result Display Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Override the `get_selected_result_label` method in your autocomplete view to display selected items differently than they appear in the list. This example shows how to return the short name for selected items while the full name is used for list results. ```python class CountryAutocomplete(autocomplete.Select2QuerySetView): def get_result_label(self, item): return item.full_name def get_selected_result_label(self, item): return item.short_name ``` -------------------------------- ### Add dal_alight_queryset_sequence for GFK support Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md If you need Generic Foreign Key support, include 'dal_queryset_sequence' and 'dal_alight_queryset_sequence' in your INSTALLED_APPS. This bridges the queryset sequence functionality with the Alight frontend. ```python INSTALLED_APPS = [ 'dal', 'dal_alight', 'dal_queryset_sequence', 'dal_alight_queryset_sequence', # bridges the two ... ] ``` -------------------------------- ### Autocomplete View Accessing Forwarded Values Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/_forward.md In the autocomplete view, access the forwarded value from 'self.forwarded' to filter the queryset. This example filters countries by continent. ```python class CountryAutocomplete(autocomplete.AlightQuerySetView): def get_queryset(self): qs = Country.objects.all() continent = self.forwarded.get('continent', None) if continent: qs = qs.filter(continent=continent) if self.q: qs = qs.filter(name__istartswith=self.q) return qs ``` -------------------------------- ### Configure INSTALLED_APPS for Django Autocomplete Light Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/install.md Add 'dal' and 'dal_alight' to your project's INSTALLED_APPS before Django's admin to ensure proper widget template overriding. ```python 'dal', 'dal_alight', # 'grappelli', 'django.contrib.admin', ``` -------------------------------- ### Register Alight QuerySetView with Model and URL Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md A simpler way to register an autocomplete view is by directly passing the model to AlightQuerySetView.as_view(). This avoids the need for a custom view class for basic model-based autocompletion. ```python from dal import autocomplete from your_countries_app.models import Country urlpatterns = [ path( 'country-autocomplete/', autocomplete.AlightQuerySetView.as_view(model=Country), name='country-autocomplete', ), ] ``` -------------------------------- ### Create a ListSelect2 Widget Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Instantiate a ListSelect2 widget, specifying the URL where the autocomplete view is registered. This widget will then display the autocomplete suggestions. ```python widget = autocomplete.ListSelect2(url='country-list-autocomplete') ``` -------------------------------- ### Reusing DAL's Field Forwarding Logic in JavaScript Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md These JavaScript functions, getFieldRelativeTo and getValueFromField, allow you to reuse DAL's logic for finding fields and getting their values when implementing custom forwarding. ```javascript yl.registerForwardHandler("poormans_field_forward", function (elem) { return yl.getValueFromField( yl.getFieldRelativeTo(elem, "some_field")); }); ``` -------------------------------- ### Autocomplete from a Simple List of Strings Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Define a view that returns a list of strings for autocomplete suggestions. This is useful for static, predefined choices. ```python class CountryAutocompleteFromList(autocomplete.Select2ListView): def get_list(self): return ['France', 'Fiji', 'Finland', 'Switzerland'] ``` -------------------------------- ### Run Tests with Pytest Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/CLAUDE.md Execute tests for Django Autocomplete Light using pytest. This command runs tests on a live server. ```bash cd test_project/ pytest -v --liveserver 127.0.0.1:9999 ``` -------------------------------- ### Configure Select2 Widget Options Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Instantiates a Select2 widget with custom options like placeholder text and minimum input length. Useful for fine-tuning autocomplete behavior. ```python autocomplete.ModelSelect2( url='select2_fk', attrs={ 'data-placeholder': 'Autocomplete ...', 'data-minimum-input-length': 3, }, ) ``` -------------------------------- ### Create an Alight QuerySet Autocomplete View Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Define a custom view inheriting from AlightQuerySetView to handle autocomplete requests. This view filters the queryset based on user authentication and the query parameter 'q'. ```python from dal import autocomplete from your_countries_app.models import Country class CountryAutocomplete(autocomplete.AlightQuerySetView): def get_queryset(self): 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 ``` -------------------------------- ### Enable On-the-Fly Object Creation in Autocomplete Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Configure your autocomplete view to allow users to create new choices directly from the form. Set `create_field` to the model field that should be used for creation. ```python urlpatterns = [ path( 'country-autocomplete/', CountryAutocomplete.as_view(create_field='name'), name='country-autocomplete', ), ] ``` -------------------------------- ### Autocompleting from a List of Strings Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Use AlightListView when results come from a plain Python list. Define the get_list method to return the list of strings. ```python class FruitAutocomplete(autocomplete.AlightListView): def get_list(self): return ['apple', 'mango', 'apricot', 'orange'] ``` -------------------------------- ### Mixing String-Based and Class-Based Forwarding Declarations Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Demonstrates how to combine different types of forwarding declarations within a single widget's forward attribute, including string-based, renamed fields, and constants. ```python 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 forward.Const(42, 'f4') # Constant forwarding (see below) ) ``` -------------------------------- ### Run Headless Tests with Pytest Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/CLAUDE.md Execute tests in a headless browser environment using pytest. This is useful for CI/CD pipelines. ```bash BROWSER=firefox MOZ_HEADLESS=1 pytest -v ``` -------------------------------- ### Allowing Creation of New List Items Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md To allow creating values not present in the initial list, define a create method on the AlightListView. The create method should return the value to be stored. ```python class FruitAutocomplete(autocomplete.AlightListView): def get_list(self): return ['apple', 'mango', 'apricot', 'orange'] def create(self, text): return text # return the stored value ``` -------------------------------- ### Add dal_alight to INSTALLED_APPS Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Ensure 'dal_alight' is added to your Django project's INSTALLED_APPS before 'django.contrib.admin'. This is a prerequisite for using the Alight frontend. ```python INSTALLED_APPS = [ 'dal', 'dal_alight', # 'grappelli', 'django.contrib.admin', ... ] ``` -------------------------------- ### Enable Creation of New Choices in Autocomplete Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Configure your URL patterns to allow users to create new objects directly from the autocomplete widget. Set `create_field` to the model field for creation and `validate_create=True` to enable full validation. ```python urlpatterns = [ path( 'country-autocomplete/', CountryAutocomplete.as_view(create_field='name', validate_create=True), name='country-autocomplete', ), ] ``` -------------------------------- ### Autocomplete View for Taggit Tags Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/taggit.md Extend AlightTagAutocompleteView to provide tag autocompletion, overriding get_result_value to match tags by name. ```python from dal import autocomplete from taggit.models import Tag class TagAutocomplete(autocomplete.AlightTagAutocompleteView): def get_queryset(self): 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 ``` -------------------------------- ### Custom Autocomplete View for Taggit Tags Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/taggit.md Alternatively, extend AlightQuerySetView directly and override get_result_value to specify how tag results are returned. ```python class TagAutocomplete(autocomplete.AlightQuerySetView): def get_result_value(self, result): return result.name ``` -------------------------------- ### Registering Autocomplete URLs for a Form Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/gfk.md Extends the urlpatterns in urls.py to include the autocomplete URLs generated by the form. This makes the autocomplete functionality accessible via URL. ```python from .forms import TestForm urlpatterns = [...] # your regular url patterns urlpatterns.extend(TestForm.as_urls()) ``` -------------------------------- ### Autocomplete with Opt-Groups from a List Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Define a view that returns a list of tuples, where each tuple contains a group name and a list of choices for that group. This enables opt-group formatting in the autocomplete suggestions. ```python class CountryAutocompleteFromList(autocomplete.Select2GroupListView): def get_list(self): return [ (None, ['Mars Colony',]), ("Country", ['France', 'Fiji', 'Finland', 'Switzerland']) ] ``` -------------------------------- ### Pre-fill Login Form Fields with JavaScript Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/test_project/templates/admin/login.html This JavaScript snippet is used within the login template to pre-fill the username and password fields with 'test' values. ```javascript document.getElementById('id_username').value = 'test'; document.getElementById('id_password').value = 'test'; ``` -------------------------------- ### Autocomplete with Opt-Groups and Custom Values Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Define a view that returns a list of tuples, where each tuple contains a group identifier and a list of choices. Each choice is itself a list containing a value and display text, allowing for custom values within opt-groups. ```python class CountryAutocompleteFromList(autocomplete.Select2GroupListView): def get_list(self): return [ ([None, None], [['Mars_colony_value', 'Mars Colony']]), ( ['Country_value', 'Country'], [ ['France_value', 'France'], ['Fiji_value', 'Fiji'], ['Finland_value', 'Finland'], ['Switzerland_value', 'Switzerland'] ] ) ] ``` -------------------------------- ### Django Template for Autocomplete Form Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md This template demonstrates how to render a form with autocomplete widgets and includes necessary JavaScript for dynamic formset handling. Ensure `{{ form.media }}` is included to load required JavaScript and CSS. ```html {% extends 'base.html' %} {# Don't forget that one ! #} {% load static %} {% block content %}
{% csrf_token %} {{ form.as_p }}
{{ view.formset }}
Add form
{% endblock %} {% block footer %} {{ form.media }} {% endblock %} ``` -------------------------------- ### Autocomplete Form with GenericForeignKeyModelField and Custom Widgets Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/gfk.md Uses FutureModelForm and GenericForeignKeyModelField with custom widgets and views for GenericForeignKey autocompletion. This provides more control over the widget and view implementation. ```python from dal import autocomplete class TestForm(autocomplete.FutureModelForm): location = autocomplete.GenericForeignKeyModelField( model_choice=[(Country,), (City,)], # Models widget=autocomplete.QuerySetSequenceAlight, view=autocomplete.AlightQuerySetSequenceView, ) class Meta: model = TestModel ``` -------------------------------- ### Widget for List Autocomplete Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Use ListAlight widget in your form, specifying the URL where the autocomplete view is registered. ```python widget = autocomplete.ListAlight(url='fruit-autocomplete') ``` -------------------------------- ### List-based Grouped Results Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Use AlightGroupListView for grouping string lists. The get_list method should return pairs of (group_name, item). Items with group=None are displayed without a header. ```python class FruitAutocomplete(autocomplete.AlightGroupListView): def get_list(self): return [ ('Tropical', 'mango'), ('Tropical', 'papaya'), ('Temperate', 'apple'), ('Temperate', 'pear'), ] ``` -------------------------------- ### Form Field for List Creation Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Use AlightListCreateChoiceField in the form to enable creating new values that are not in the initial choice list. This ensures submitted values pass validation. ```python from dal import autocomplete class FruitForm(forms.ModelForm): fruit = autocomplete.AlightListCreateChoiceField( choice_list=['apple', 'mango', 'apricot', 'orange'], widget=autocomplete.ListAlight(url='fruit-autocomplete'), ) ``` -------------------------------- ### Automate FormField with djhacker and ModelAlight Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Utilize the djhacker library to automatically configure a form field with the ModelAlight widget. This is useful for integrating autocompletion into existing Django models without modifying the forms directly. ```python import djhacker # pip install djhacker from django import forms djhacker.formfield( Person.birth_country, forms.ModelChoiceField, widget=autocomplete.ModelAlight(url='country-autocomplete') ) ``` -------------------------------- ### Registering Auto-Generated URLs Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Register the auto-generated URLs for the form using its as_urls() method in your project's urls.py. ```python from .forms import TestForm urlpatterns += TestForm.as_urls() ``` -------------------------------- ### Customizing Forwarding with JavaScript Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Use this to integrate custom JavaScript forwarding logic for non-standard fields. The registered handler's return value is forwarded to the autocomplete view with a specified destination name. ```python from dal import forward class ShippingForm(forms.Form): country = forms.ModelChoiceField( queryset=Country.objects.all(), widget=autocomplete.ModelSelect2( url='country-autocomplete', forward=(forward.JavaScript('my_awesome_handler', 'magic_number'),))) ``` -------------------------------- ### Register Alight Autocomplete View with URL Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Register the custom autocomplete view in your Django urls.py. This maps a URL path to your autocomplete view, making it accessible for form widgets. ```python from django.urls import path from your_countries_app.views import CountryAutocomplete urlpatterns = [ path( 'country-autocomplete/', CountryAutocomplete.as_view(), name='country-autocomplete', ), ] ``` -------------------------------- ### Configure ModelForm Widget for ForeignKey Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md This sets up the autocomplete form widget for a ForeignKey field using ModelSelect2, linking it to the registered 'country-autocomplete' URL. ```python from dal import autocomplete from django import forms class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('__all__') widgets = { 'birth_country': autocomplete.ModelSelect2(url='country-autocomplete') } ``` -------------------------------- ### Autocomplete with Custom Values from a List Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Define a view that returns a list of lists or tuples, where each inner item contains a value and a display text. This allows for custom values distinct from the displayed text. ```python class CountryAutocompleteFromList(autocomplete.Select2ListView): def get_list(self): return [ ['France_value', 'France'], ['Fiji_value', 'Fiji'], ['Finland_value', 'Finland'], ['Switzerland_value', 'Switzerland'] ] ``` -------------------------------- ### Create a Select2 QuerySet Autocomplete View Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md This view serves suggestions for a Select2 widget, filtering results based on user authentication and query input. It uses Django's class-based views and Mixins. ```python from dal import autocomplete from your_countries_app.models import Country 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 ``` -------------------------------- ### Autocomplete Form with AlightGenericForeignKeyModelField Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/gfk.md Uses FutureModelForm and AlightGenericForeignKeyModelField to enable autocompletion for a GenericForeignKey. It allows filtering based on related model attributes. ```python from dal import autocomplete # don't forget to pip install django-autocomplete-light[gfk] class TestForm(autocomplete.FutureModelForm): location = autocomplete.AlightGenericForeignKeyModelField( # Model with values to filter, linked with the name field model_choice=[(Country, 'country_code', [('language', 'spoken_language'),]), (City, 'name')], ) class Meta: model = TestModel ``` -------------------------------- ### Using Self() for Forwarding Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md A shortcut provided by DAL to forward the value from the same field. The value will be available in the autocomplete view as 'self.forwarded['self']'. ```python from dal import forward class SomeForm(forms.Form): countries = forms.ModelMultipleChoiceField( queryset=Country.objects.all(), widget=autocomplete.ModelSelect2Multiple( url='country-autocomplete', forward=(forward.Self(),) ``` -------------------------------- ### Django Admin Base Template Structure Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/test_project/templates/admin/base_site.html This snippet shows the basic Django template inheritance for the admin site. It includes blocks for title, branding, navigation, and extra head content. ```html {% extends "admin/base.html" %} {% load i18n static %} {% block title %}{{ title }} | {{ site_header|default:">_('Django administration')" }}{% endblock %} {% block branding %} {{ site_header|default:">_('Django administration')" }} {% url 'admin:index' %} {% if user.is_anonymous %} {% include "admin/color_theme_toggle.html" %} {% endif %} {% endblock %} {% block nav-global %} {% if user.is_staff %} {% endif %} {% endblock %} {% block extrahead %} {{ block.super }} ``` -------------------------------- ### Validate New Objects Before Creation Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md To ensure data integrity, add `validate_create=True` to your autocomplete view configuration. This will run the model's `full_clean()` method before saving any newly created objects. ```python CountryAutocomplete.as_view(create_field='name', validate_create=True) ``` -------------------------------- ### Taggit Integration Widget Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Use TaggitAlight widget in your form for django-taggit integration. Provide the URL for your taggit autocomplete view. ```python from dal import autocomplete class TestForm(autocomplete.FutureModelForm): class Meta: model = TestModel fields = ('name',) widgets = { 'tags': autocomplete.TaggitAlight('your-taggit-autocomplete-url') } ``` -------------------------------- ### Forwarding Arbitrary Constant Values Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Shows how to forward a constant value ('europe') as a specific field name ('continent') without adding extra hidden fields to the form. This is useful for setting default or fixed parameters. ```python from dal import forward class EuropeanShippingForm(forms.Form): src_country = forms.ModelChoiceField( queryset=Country.objects.all(), widget=autocomplete.ModelSelect2( url='country-autocomplete', forward=(forward.Const('europe', 'continent'),))) ``` -------------------------------- ### Register Custom JavaScript Initialization Function Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Register a custom JavaScript function to be called when Django Autocomplete Light initializes a widget. This is useful for custom logic that needs to run after initialization, especially with dynamically added form elements. The function receives the jQuery object and the input DOM element as arguments. ```javascript document.addEventListener('dal-init-function', function () { yl.registerFunction( 'select2', function ($, element) { // autocomplete function here }); }) ``` ```python class YourWidget(ModelSelect2): autocomplete_function = 'your_autocomplete_function' ``` ```javascript document.addEventListener('dal-init-function', function () { yl.registerFunction( 'your_autocomplete_function', function ($, element) { var $element = $(element); // autocomplete function here }); }) ``` -------------------------------- ### ModelForm with Forwarded Widget Argument Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/_forward.md Define a ModelForm and specify the 'forward' argument for the autocomplete widget to link it with another form field. ```python class PersonForm(forms.ModelForm): continent = forms.ChoiceField(choices=CONTINENT_CHOICES) class Meta: model = Person fields = ('__all__',) widgets = { 'birth_country': autocomplete.ModelAlight( url='country-autocomplete', forward=['continent'], ) } ``` -------------------------------- ### Configure TabularInline with Custom Form Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Use a custom form, which includes Alight autocomplete widgets, within a Django TabularInline. This allows for autocompletion fields to be used in inline editing scenarios. ```python class PersonInline(admin.TabularInline): model = Person form = PersonForm ``` -------------------------------- ### Display Custom HTML in Autocomplete Results Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Renders custom HTML for autocomplete results by setting `data-html: true` on the widget and overriding `get_result_label` in the view. Use `format_html` to prevent XSS attacks. ```python from django.utils.html import format_html class CountryAutocomplete(autocomplete.Select2QuerySetView): def get_result_label(self, result): return format_html(' {}', result.name, result.name) class PersonForm(forms.ModelForm): class Meta: widgets = { 'birth_country': autocomplete.ModelSelect2( url='country-autocomplete', attrs={'data-html': True} ) } ``` -------------------------------- ### QuerySet-backed Grouped Results Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Use AlightGroupQuerySetView to display QuerySet results grouped by a related field. Set group_by_related to the ForeignKey field name and optionally related_field_name for the label attribute. ```python class CountryAutocomplete(autocomplete.AlightGroupQuerySetView): group_by_related = 'continent' related_field_name = 'name' def get_queryset(self): return Country.objects.all() ``` -------------------------------- ### Configure ModelForm Widget for ManyToMany Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md This configures the autocomplete form widget for a ManyToMany field using ModelSelect2Multiple, connecting it to the 'country-autocomplete' URL. ```python widgets = { 'visited_countries': autocomplete.ModelSelect2Multiple(url='country-autocomplete') } ``` -------------------------------- ### Form Widget for Taggit Tags Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/taggit.md Use TaggitAlight widget in a Django form to enable tag autocompletion for a TaggableManager field. ```python from dal import autocomplete class TestForm(autocomplete.FutureModelForm): class Meta: model = TestModel fields = ('name',) widgets = { 'tags': autocomplete.TaggitAlight( 'your-taggit-autocomplete-url' ) } ``` -------------------------------- ### JavaScript Event Listener for Autocomplete Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/test_project/templates/admin/base_site.html This JavaScript code listens for the 'autocompleteChoiceSelected' event. When a choice is selected, it checks for a 'url' dataset attribute on the choice and redirects the window to that URL if found. ```javascript document.addEventListener('autocompleteChoiceSelected', function(ev) { var url = ev.detail.choice.dataset.url if (url) window.location.href = url }) ``` -------------------------------- ### Manual Generic Foreign Key Form Field Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Configure a Generic Foreign Key field manually using GenericForeignKeyModelField, specifying the widget and view. This offers more control over the autocomplete behavior. ```python from dal import autocomplete from dal_alight_queryset_sequence.views import AlightQuerySetSequenceView from dal_alight_queryset_sequence.widgets import QuerySetSequenceAlight class TestForm(autocomplete.FutureModelForm): location = autocomplete.GenericForeignKeyModelField( model_choice=[(Country,), (City,)], widget=QuerySetSequenceAlight, view=AlightQuerySetSequenceView, ) class Meta: model = TestModel ``` -------------------------------- ### Use ModelAlight Widget for ForeignKey Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/alight.md Integrate the ModelAlight widget into a Django ModelForm for ForeignKey fields. This widget connects the form field to the specified autocomplete URL. ```python from dal import autocomplete from django import forms class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('__all__',) widgets = { 'birth_country': autocomplete.ModelAlight(url='country-autocomplete') } ``` -------------------------------- ### Registering a JavaScript Forward Handler Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/docs/tutorial.md Register a custom JavaScript function to handle value forwarding for non-standard fields. The handler receives the autocomplete HTML element as an argument. ```javascript // autocompleteElem here is an HTML element for autocomplete field yl.registerForwardHandler("my_awesome_handler", function (autocompleteElem) { return doSomeMagicAndGetValueFromSpace(); }); ``` -------------------------------- ### Django Admin Login Template Structure Source: https://github.com/yourlabs/django-autocomplete-light/blob/master/test_project/templates/admin/login.html This is the main structure of the Django admin login template, extending the base site and defining various blocks. ```html {% extends "admin/base\_site.html" %} {% load i18n static %} {% block extrastyle %}{{ block.super }} {{ form.media }} {% endblock %} {% block bodyclass %}{{ block.super }} login{% endblock %} {% block usertools %}{% endblock %} {% block nav-global %}{% endblock %} {% block content_title %}{% endblock %} {% block breadcrumbs %}{% endblock %} {% block content %} {% if form.errors and not form.non_field_errors %} {% if form.errors.items|length == 1 %}{% trans "Please correct the error below." %}{% else %}{% trans "Please correct the errors below." %}{% endif %} {% endif %} {% if form.non_field_errors %} {% for error in form.non_field_errors %} {{ error }} {% endfor %} {% endif %} {% if user.is_authenticated %} {% blocktrans with username=request.user.username trimmed %} You are authenticated as {{ username }}, but are not authorized to access this page. Would you like to login to a different account? {% endblocktrans %} {% endif %} {% csrf_token %} {{ form.username.errors }} {{ form.username.label_tag }} {{ form.username }} {{ form.password.errors }} {{ form.password.label_tag }} {{ form.password }} {% url 'admin_password_reset' as password_reset_url %} {% if password_reset_url %} [{% trans 'Forgotten your password or username?' %}]({{ password_reset_url }}) {% endif %} {% endblock %} ```