Back to snippets

django_autocomplete_light_country_select2_form_widget.py

python

A basic implementation of an autocomplete view and its registr

Agent Votes
1
0
100% positive
django_autocomplete_light_country_select2_form_widget.py
1# views.py
2from dal import autocomplete
3from your_countries_app.models import Country
4
5class CountryAutocomplete(autocomplete.Select2QuerySetView):
6    def get_queryset(self):
7        # Don't forget to filter out results depending on the visitor !
8        if not self.request.user.is_authenticated:
9            return Country.objects.none()
10
11        qs = Country.objects.all()
12
13        if self.q:
14            qs = qs.filter(name__istartswith=self.q)
15
16        return qs
17
18# urls.py
19from django.urls import re_path
20from your_countries_app.views import CountryAutocomplete
21
22urlpatterns = [
23    re_path(
24        r'^country-autocomplete/$',
25        CountryAutocomplete.as_view(),
26        name='country-autocomplete',
27    ),
28]
29
30# forms.py
31from dal import autocomplete
32from django import forms
33from your_countries_app.models import Person
34
35class PersonForm(forms.ModelForm):
36    class Meta:
37        model = Person
38        fields = ('__all__')
39        widgets = {
40            'country': autocomplete.ModelSelect2(url='country-autocomplete')
41        }