forms.py 5.1 KB

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