Skip to content

Instantly share code, notes, and snippets.



Last active Aug 5, 2016
What would you like to do?
Generic autocompletes for django-autocomplete-light v3.x
from django.conf.urls import include, url
from django.views.generic import TemplateView
from parlhand.views import ParliamentSearchView
from parlhand import views
urlpatterns = [
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import get_object_or_404
class GenericAutocomplete(autocomplete.Select2QuerySetView):
model = None
template_name = "autocomplete_light/item.html"
def dispatch(self, request, *args, **kwargs):
self.property_name = kwargs.pop('property_name', 'pk')
if 'app_name' in kwargs.keys() and 'model_name' in kwargs.keys():
self.model = get_object_or_404(
ContentType, app_label=kwargs['app_name'], model=kwargs['model_name']
return super(GenericAutocomplete, self).dispatch(request, *args, **kwargs)
def get_queryset(self):
# Don't forget to filter out results depending on the visitor !
if not self.request.user.is_authenticated():
return self.model.objects.none()
qs = self.model.objects.all()
if self.q:
qs = qs.filter(**{'%s__icontains'%self.property_name: self.q})
return qs
def get_result_label(self, result):
"""Return the label of a result."""
template = get_template(self.template_name)
context = Context({"item": result})
return template.render(context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment