You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

autocomplete.py 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from django.http import Http404, JsonResponse
  2. from django.views.generic.list import BaseListView
  3. class AutocompleteJsonView(BaseListView):
  4. """Handle AutocompleteWidget's AJAX requests for data."""
  5. paginate_by = 20
  6. model_admin = None
  7. def get(self, request, *args, **kwargs):
  8. """
  9. Return a JsonResponse with search results of the form:
  10. {
  11. results: [{id: "123" text: "foo"}],
  12. pagination: {more: true}
  13. }
  14. """
  15. if not self.model_admin.get_search_fields(request):
  16. raise Http404(
  17. '%s must have search_fields for the autocomplete_view.' %
  18. type(self.model_admin).__name__
  19. )
  20. if not self.has_perm(request):
  21. return JsonResponse({'error': '403 Forbidden'}, status=403)
  22. self.term = request.GET.get('term', '')
  23. self.paginator_class = self.model_admin.paginator
  24. self.object_list = self.get_queryset()
  25. context = self.get_context_data()
  26. return JsonResponse({
  27. 'results': [
  28. {'id': str(obj.pk), 'text': str(obj)}
  29. for obj in context['object_list']
  30. ],
  31. 'pagination': {'more': context['page_obj'].has_next()},
  32. })
  33. def get_paginator(self, *args, **kwargs):
  34. """Use the ModelAdmin's paginator."""
  35. return self.model_admin.get_paginator(self.request, *args, **kwargs)
  36. def get_queryset(self):
  37. """Return queryset based on ModelAdmin.get_search_results()."""
  38. qs = self.model_admin.get_queryset(self.request)
  39. qs, search_use_distinct = self.model_admin.get_search_results(self.request, qs, self.term)
  40. if search_use_distinct:
  41. qs = qs.distinct()
  42. return qs
  43. def has_perm(self, request, obj=None):
  44. """Check if user has permission to access the related model."""
  45. return self.model_admin.has_view_permission(request, obj=obj)