filters.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. from django.contrib.admin import RelatedFieldListFilter
  2. from django.utils.encoding import smart_text
  3. from django.utils.html import format_html
  4. from django.core.urlresolvers import reverse
  5. try:
  6. from django.contrib.admin.utils import get_model_from_relation
  7. except ImportError: # Django 1.6
  8. from django.contrib.admin.util import get_model_from_relation
  9. try:
  10. from django.forms.utils import flatatt
  11. except ImportError: # Django 1.6
  12. from django.forms.util import flatatt
  13. class RelatedFieldAjaxListFilter(RelatedFieldListFilter):
  14. template = 'jet/related_field_ajax_list_filter.html'
  15. ajax_attrs = None
  16. def has_output(self):
  17. return True
  18. def field_choices(self, field, request, model_admin):
  19. model = field.remote_field.model if hasattr(field, 'remote_field') else field.related_field.model
  20. app_label = model._meta.app_label
  21. model_name = model._meta.object_name
  22. self.ajax_attrs = format_html('{0}', flatatt({
  23. 'data-app-label': app_label,
  24. 'data-model': model_name,
  25. 'data-ajax--url': reverse('jet:model_lookup'),
  26. 'data-queryset--lookup': self.lookup_kwarg
  27. }))
  28. if self.lookup_val is None:
  29. return []
  30. other_model = get_model_from_relation(field)
  31. if hasattr(field, 'rel'):
  32. rel_name = field.rel.get_related_field().name
  33. else:
  34. rel_name = other_model._meta.pk.name
  35. queryset = model._default_manager.filter(**{rel_name: self.lookup_val}).all()
  36. return [(x._get_pk_val(), smart_text(x)) for x in queryset]
  37. try:
  38. from collections import OrderedDict
  39. from django import forms
  40. from django.contrib.admin.widgets import AdminDateWidget
  41. from rangefilter.filter import DateRangeFilter as OriginalDateRangeFilter
  42. from django.utils.translation import ugettext as _
  43. class DateRangeFilter(OriginalDateRangeFilter):
  44. def get_template(self):
  45. return 'rangefilter/date_filter.html'
  46. def _get_form_fields(self):
  47. # this is here, because in parent DateRangeFilter AdminDateWidget
  48. # could be imported from django-suit
  49. return OrderedDict((
  50. (self.lookup_kwarg_gte, forms.DateField(
  51. label='',
  52. widget=AdminDateWidget(attrs={'placeholder': _('From date')}),
  53. localize=True,
  54. required=False
  55. )),
  56. (self.lookup_kwarg_lte, forms.DateField(
  57. label='',
  58. widget=AdminDateWidget(attrs={'placeholder': _('To date')}),
  59. localize=True,
  60. required=False
  61. )),
  62. ))
  63. @staticmethod
  64. def _get_media():
  65. css = [
  66. 'style.css',
  67. ]
  68. return forms.Media(
  69. css={'all': ['range_filter/css/%s' % path for path in css]}
  70. )
  71. except ImportError:
  72. pass