forms.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import json
  2. from django import forms
  3. from django.core.exceptions import ValidationError
  4. from django.db.models import Q
  5. import operator
  6. from jet.models import Bookmark, PinnedApplication
  7. from jet.utils import get_model_instance_label
  8. from functools import reduce
  9. try:
  10. from django.apps import apps
  11. get_model = apps.get_model
  12. except ImportError:
  13. from django.db.models.loading import get_model
  14. class AddBookmarkForm(forms.ModelForm):
  15. def __init__(self, request, *args, **kwargs):
  16. self.request = request
  17. super(AddBookmarkForm, self).__init__(*args, **kwargs)
  18. class Meta:
  19. model = Bookmark
  20. fields = ['url', 'title']
  21. def clean(self):
  22. data = super(AddBookmarkForm, self).clean()
  23. if not self.request.user.is_authenticated():
  24. raise ValidationError('error')
  25. if not self.request.user.has_perm('jet.change_bookmark'):
  26. raise ValidationError('error')
  27. return data
  28. def save(self, commit=True):
  29. self.instance.user = self.request.user.pk
  30. return super(AddBookmarkForm, self).save(commit)
  31. class RemoveBookmarkForm(forms.ModelForm):
  32. def __init__(self, request, *args, **kwargs):
  33. self.request = request
  34. super(RemoveBookmarkForm, self).__init__(*args, **kwargs)
  35. class Meta:
  36. model = Bookmark
  37. fields = []
  38. def clean(self):
  39. data = super(RemoveBookmarkForm, self).clean()
  40. if not self.request.user.is_authenticated():
  41. raise ValidationError('error')
  42. if self.instance.user != self.request.user.pk:
  43. raise ValidationError('error')
  44. return data
  45. def save(self, commit=True):
  46. if commit:
  47. self.instance.delete()
  48. class ToggleApplicationPinForm(forms.ModelForm):
  49. def __init__(self, request, *args, **kwargs):
  50. self.request = request
  51. super(ToggleApplicationPinForm, self).__init__(*args, **kwargs)
  52. class Meta:
  53. model = PinnedApplication
  54. fields = ['app_label']
  55. def save(self, commit=True):
  56. if commit:
  57. try:
  58. pinned_app = PinnedApplication.objects.get(
  59. app_label=self.cleaned_data['app_label'],
  60. user=self.request.user.pk
  61. )
  62. pinned_app.delete()
  63. return False
  64. except PinnedApplication.DoesNotExist:
  65. PinnedApplication.objects.create(
  66. app_label=self.cleaned_data['app_label'],
  67. user=self.request.user.pk
  68. )
  69. return True
  70. class ModelLookupForm(forms.Form):
  71. app_label = forms.CharField()
  72. model = forms.CharField()
  73. q = forms.CharField(required=False)
  74. page = forms.IntegerField(required=False)
  75. page_size = forms.IntegerField(required=False, min_value=1, max_value=1000)
  76. object_id = forms.IntegerField(required=False)
  77. model_cls = None
  78. def clean(self):
  79. data = super(ModelLookupForm, self).clean()
  80. try:
  81. self.model_cls = get_model(data['app_label'], data['model'])
  82. except:
  83. raise ValidationError('error')
  84. return data
  85. def lookup(self):
  86. qs = self.model_cls.objects
  87. if self.cleaned_data['q']:
  88. if getattr(self.model_cls, 'autocomplete_search_fields', None):
  89. search_fields = self.model_cls.autocomplete_search_fields()
  90. filter_data = [Q((field + '__icontains', self.cleaned_data['q'])) for field in search_fields]
  91. # if self.cleaned_data['object_id']:
  92. # filter_data.append(Q(pk=self.cleaned_data['object_id']))
  93. qs = qs.filter(reduce(operator.or_, filter_data))
  94. else:
  95. qs = qs.none()
  96. limit = self.cleaned_data['page_size'] or 100
  97. page = self.cleaned_data['page'] or 1
  98. offset = (page - 1) * limit
  99. items = list(map(
  100. lambda instance: {'id': instance.pk, 'text': get_model_instance_label(instance)},
  101. qs.all()[offset:offset + limit]
  102. ))
  103. total = qs.count()
  104. return items, total