autocomplete.rst 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. ============
  2. Autocomplete
  3. ============
  4. By default Django JET renders all possible choices for select inputs. This behavior may be unwanted if number of
  5. available options is rather big. In this case Django JET allows you to load these options dynamically through AJAX.
  6. Configuration
  7. -------------
  8. In order to achieve this functionality all you have to do is:
  9. -
  10. Specify which model fields should be searchable by AJAX queries. Add this static method which must return
  11. a ``tuple`` or ``list`` of fields you want to be searchable with AJAX:
  12. .. code:: python
  13. @staticmethod
  14. def autocomplete_search_fields():
  15. return 'field1', 'field2'
  16. # for single field
  17. @staticmethod
  18. def autocomplete_search_fields():
  19. return 'field1',
  20. Example from Django JET demo site:
  21. .. code:: python
  22. class Address(models.Model):
  23. name = models.CharField(_('name'), max_length=255)
  24. city = models.ForeignKey(City, verbose_name=_('city'), related_name='addresses')
  25. zip = models.IntegerField(_('zip/postal code'))
  26. class Meta:
  27. verbose_name = _('address')
  28. verbose_name_plural = _('addresses')
  29. unique_together = ('name', 'city')
  30. def __str__(self):
  31. return self.name
  32. @staticmethod
  33. def autocomplete_search_fields():
  34. return 'name', 'city__name'
  35. - Use custom AJAX filter class ``jet.filters.RelatedFieldAjaxListFilter`` if you have any foreign key list filters:
  36. .. code:: python
  37. from jet.filters import RelatedFieldAjaxListFilter
  38. class PersonAdmin(admin.ModelAdmin):
  39. list_filter = (
  40. ...
  41. ('address', RelatedFieldAjaxListFilter),
  42. )
  43. - Now all your admin select boxes will perform AJAX queries to load available options while you type.
  44. .. note::
  45. This work for both ForeignKey and ManyToManyField fields.
  46. Disabling Autocomplete For Form Fields
  47. --------------------------------------
  48. Autocomplete is nice, but sometimes you don't want this behaviour (e.x. because you want to limit the provided
  49. queryset for a particular widget). In this case you can disable autocompletion this way:
  50. .. code:: python
  51. class YourForm(forms.ModelForm):
  52. def __init__(self, *args, **kwargs):
  53. super(YourForm, self).__init__(*args, **kwargs)
  54. if SOME_CASE(self.instance):
  55. self.fields['FIELD_NAME'].autocomplete = False
  56. self.fields['FIELD_NAME'].queryset = Model.queryset.some_filter()