### 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 %}
{}', 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 %}
```