yourlabs / django-autocomplete-light

A fresh approach to autocomplete implementations, specially for Django. Status: v4 alpha, v3 stable, v2 & v1 deprecated.
https://django-autocomplete-light.readthedocs.io
MIT License
1.79k stars 467 forks source link

Autocomplete field registry is back with djhacker! #1271

Closed jpic closed 2 years ago

jpic commented 2 years ago

The awesome feature back from the old days, except way simpler and thus, maintainable!

While you can use the widget as usual with Django, as it will be described in the next examples, here we're going to see how to make a specific model field automatically generate the autocomplete field using that view, using the djhacker <https://yourlabs.io/oss/djhacker>_ module.

.. code-block:: python

# Register your autocomplete view as usual
urlpatterns = [
    url(
        'test-autocomplete/$',
        autocomplete.Select2QuerySetView.as_view(model=TModel),
        name='select2_djhacker_formfield',
    ),
]

# Now hack your model field to always render the autocomplete field with
# that view!
import djhacker
from django import forms
djhacker.formfield(
    TModel.test,
    forms.ModelChoiceField,
    widget=autocomplete.ModelSelect2(url='select2_djhacker_formfield')
)

The above example demonstrates how to integrate your autocomplete view and form field automatically throughout Django without having to define custom model forms all the time.