The Python Oracle

django-autocomplete-light simple usage

This video explains
django-autocomplete-light simple usage

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 Question
01:18 Accepted answer (Score 20)
03:21 Thank you

--

Full question
https://stackoverflow.com/questions/1447...

Question links:
[django-autocomplete-light]: https://github.com/yourlabs/django-autoc...

Accepted answer links:
[the select widget should be used by default]: https://docs.djangoproject.com/en/dev/re...
[django docs about using widgets]: https://docs.djangoproject.com/en/dev/re.../
[specify the widget]: http://django-autocomplete-light.readthe...
[shortcuts like ]: http://django-autocomplete-light.readthe...
[API docs]: http://django-autocomplete-light.readthe...
[reading the source code]: https://github.com/yourlabs/django-autoc...
[the cookbook]: https://django-autocomplete-light.readth...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django #autocomplete #djangoautocompletelight

#avk47



ACCEPTED ANSWER

Score 20


Select widget is default for ModelChoiceField

This form field does not specify a widget, so the select widget should be used by default with:

mymodel = forms.ModelChoiceField(
                required=True,
                queryset=ships.models.Authority.objects.all(),
          ) 

This is why you see a select field instead of an autocomplete.

Did you read django docs about using widgets ?

Use autocomplete_light.ChoiceWidget instead

All you have to do is specify the widget:

mymodel = forms.ModelChoiceField(
            required=True,
            queryset=ships.models.Authority.objects.all(),
            widget=autocomplete_light.ChoiceWidget('AutocompleteName')
          ) 

If you don't know what is the name of the autocomplete, login as staff and open http://yoursite/autocomplete/.

Ensure that you have jquery properly loaded and that autocomplete-light's staticfiles are loaded too !

Alternatives

FTR: another way is possible, using autocomplete_light.modelform_factory using shortcuts like autocomplete_light.modelform_factory or autocomplete_light.get_widgets_dict. API docs are passable but it does not beat reading the source code.

All in all, I think the easiest for you is using the get_widgets_dict shortcut if you are using a ModelForm.

Hidden docs

You might not have found the cookbook because it is a work in progress in the docs_rewrite branch, but the second part of "High level basics" provides several examples of using the widget.

I know that the docs have a problem, hence the docs_rewrite branch. Right now I'm focusing on improving mobile support.