forms.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import json
  2. from django import forms
  3. from django.core.exceptions import ValidationError
  4. from django.db.models import Q
  5. try:
  6. from django.apps import apps
  7. get_model = apps.get_model
  8. except ImportError:
  9. from django.db.models.loading import get_model
  10. import operator
  11. from jet.models import Bookmark, PinnedApplication, UserDashboardModule
  12. from jet.utils import get_current_dashboard, get_model_instance_label
  13. from functools import reduce
  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 UpdateDashboardModulesForm(forms.Form):
  71. app_label = forms.CharField(required=False)
  72. modules = forms.CharField()
  73. modules_objects = []
  74. def __init__(self, request, *args, **kwargs):
  75. self.request = request
  76. super(UpdateDashboardModulesForm, self).__init__(*args, **kwargs)
  77. def clean(self):
  78. data = super(UpdateDashboardModulesForm, self).clean()
  79. try:
  80. modules = json.loads(data['modules'])
  81. for module in modules:
  82. db_module = UserDashboardModule.objects.get(
  83. user=self.request.user.pk,
  84. app_label=data['app_label'] if data['app_label'] else None,
  85. pk=module['id']
  86. )
  87. column = module['column']
  88. order = module['order']
  89. if db_module.column != column or db_module.order != order:
  90. db_module.column = column
  91. db_module.order = order
  92. self.modules_objects.append(db_module)
  93. except Exception:
  94. raise ValidationError('error')
  95. return data
  96. def save(self):
  97. for module in self.modules_objects:
  98. module.save()
  99. class AddUserDashboardModuleForm(forms.ModelForm):
  100. type = forms.CharField()
  101. module = forms.IntegerField()
  102. module_cls = None
  103. def __init__(self, request, *args, **kwargs):
  104. self.request = request
  105. super(AddUserDashboardModuleForm, self).__init__(*args, **kwargs)
  106. class Meta:
  107. model = UserDashboardModule
  108. fields = ['app_label']
  109. def clean_app_label(self):
  110. data = self.cleaned_data['app_label']
  111. return data if data != '' else None
  112. def clean(self):
  113. data = super(AddUserDashboardModuleForm, self).clean()
  114. index_dashboard_cls = get_current_dashboard('app_index' if data['app_label'] else 'index')
  115. index_dashboard = index_dashboard_cls({'request': self.request}, app_label=data['app_label'])
  116. if data['type'] == 'children':
  117. module = index_dashboard.children[data['module']]
  118. elif data['type'] == 'available_children':
  119. module = index_dashboard.available_children[data['module']]()
  120. else:
  121. raise ValidationError('error')
  122. self.module_cls = module
  123. return data
  124. def save(self, commit=True):
  125. self.instance.title = self.module_cls.title
  126. self.instance.module = self.module_cls.fullname()
  127. self.instance.user = self.request.user.pk
  128. self.instance.column = 0
  129. self.instance.order = -1
  130. self.instance.settings = self.module_cls.dump_settings()
  131. self.instance.children = self.module_cls.dump_children()
  132. return super(AddUserDashboardModuleForm, self).save(commit)
  133. class UpdateDashboardModuleCollapseForm(forms.ModelForm):
  134. def __init__(self, request, *args, **kwargs):
  135. self.request = request
  136. super(UpdateDashboardModuleCollapseForm, self).__init__(*args, **kwargs)
  137. class Meta:
  138. model = UserDashboardModule
  139. fields = ['collapsed']
  140. def clean(self):
  141. data = super(UpdateDashboardModuleCollapseForm, self).clean()
  142. if self.instance.user != self.request.user.pk:
  143. raise ValidationError('error')
  144. return data
  145. class RemoveDashboardModuleForm(forms.ModelForm):
  146. def __init__(self, request, *args, **kwargs):
  147. self.request = request
  148. super(RemoveDashboardModuleForm, self).__init__(*args, **kwargs)
  149. class Meta:
  150. model = UserDashboardModule
  151. fields = []
  152. def clean(self):
  153. cleaned_data = super(RemoveDashboardModuleForm, self).clean()
  154. if self.instance.user != self.request.user.pk:
  155. raise ValidationError('error')
  156. return cleaned_data
  157. def save(self, commit=True):
  158. if commit:
  159. self.instance.delete()
  160. class ModelLookupForm(forms.Form):
  161. app_label = forms.CharField()
  162. model = forms.CharField()
  163. q = forms.CharField(required=False)
  164. page = forms.IntegerField(required=False)
  165. page_size = forms.IntegerField(required=False, min_value=1, max_value=1000)
  166. object_id = forms.IntegerField(required=False)
  167. model_cls = None
  168. def clean(self):
  169. data = super(ModelLookupForm, self).clean()
  170. try:
  171. self.model_cls = get_model(data['app_label'], data['model'])
  172. except:
  173. raise ValidationError('error')
  174. return data
  175. def lookup(self):
  176. qs = self.model_cls.objects
  177. if self.cleaned_data['q']:
  178. if getattr(self.model_cls, 'autocomplete_search_fields', None):
  179. search_fields = self.model_cls.autocomplete_search_fields()
  180. filter_data = [Q((field + '__icontains', self.cleaned_data['q'])) for field in search_fields]
  181. # if self.cleaned_data['object_id']:
  182. # filter_data.append(Q(pk=self.cleaned_data['object_id']))
  183. qs = qs.filter(reduce(operator.or_, filter_data))
  184. else:
  185. qs = qs.none()
  186. limit = self.cleaned_data['page_size'] or 100
  187. page = self.cleaned_data['page'] or 1
  188. offset = (page - 1) * limit
  189. items = list(map(
  190. lambda instance: {'id': instance.pk, 'text': get_model_instance_label(instance)},
  191. qs.all()[offset:offset + limit]
  192. ))
  193. total = qs.count()
  194. return items, total