forms.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 save(self, commit=True):
  22. self.instance.user = self.request.user.pk
  23. return super(AddBookmarkForm, self).save(commit)
  24. class RemoveBookmarkForm(forms.ModelForm):
  25. def __init__(self, request, *args, **kwargs):
  26. self.request = request
  27. super(RemoveBookmarkForm, self).__init__(*args, **kwargs)
  28. class Meta:
  29. model = Bookmark
  30. fields = []
  31. def clean(self):
  32. cleaned_data = super(RemoveBookmarkForm, self).clean()
  33. if self.instance.user != self.request.user.pk:
  34. raise ValidationError('error')
  35. return cleaned_data
  36. def save(self, commit=True):
  37. if commit:
  38. self.instance.delete()
  39. class ToggleApplicationPinForm(forms.ModelForm):
  40. def __init__(self, request, *args, **kwargs):
  41. self.request = request
  42. super(ToggleApplicationPinForm, self).__init__(*args, **kwargs)
  43. class Meta:
  44. model = PinnedApplication
  45. fields = ['app_label']
  46. def save(self, commit=True):
  47. if commit:
  48. try:
  49. pinned_app = PinnedApplication.objects.get(
  50. app_label=self.cleaned_data['app_label'],
  51. user=self.request.user.pk
  52. )
  53. pinned_app.delete()
  54. return False
  55. except PinnedApplication.DoesNotExist:
  56. PinnedApplication.objects.create(
  57. app_label=self.cleaned_data['app_label'],
  58. user=self.request.user.pk
  59. )
  60. return True
  61. class UpdateDashboardModulesForm(forms.Form):
  62. app_label = forms.CharField(required=False)
  63. modules = forms.CharField()
  64. modules_objects = []
  65. def __init__(self, request, *args, **kwargs):
  66. self.request = request
  67. super(UpdateDashboardModulesForm, self).__init__(*args, **kwargs)
  68. def clean(self):
  69. data = super(UpdateDashboardModulesForm, self).clean()
  70. try:
  71. modules = json.loads(data['modules'])
  72. for module in modules:
  73. db_module = UserDashboardModule.objects.get(
  74. user=self.request.user.pk,
  75. app_label=data['app_label'] if data['app_label'] else None,
  76. pk=module['id']
  77. )
  78. column = module['column']
  79. order = module['order']
  80. if db_module.column != column or db_module.order != order:
  81. db_module.column = column
  82. db_module.order = order
  83. self.modules_objects.append(db_module)
  84. except Exception:
  85. raise ValidationError('error')
  86. return data
  87. def save(self):
  88. for module in self.modules_objects:
  89. module.save()
  90. class AddUserDashboardModuleForm(forms.ModelForm):
  91. type = forms.CharField()
  92. module = forms.IntegerField()
  93. module_cls = None
  94. def __init__(self, request, *args, **kwargs):
  95. self.request = request
  96. super(AddUserDashboardModuleForm, self).__init__(*args, **kwargs)
  97. class Meta:
  98. model = UserDashboardModule
  99. fields = ['app_label']
  100. def clean_app_label(self):
  101. data = self.cleaned_data['app_label']
  102. return data if data != '' else None
  103. def clean(self):
  104. data = super(AddUserDashboardModuleForm, self).clean()
  105. index_dashboard_cls = get_current_dashboard('app_index' if data['app_label'] else 'index')
  106. index_dashboard = index_dashboard_cls({'request': self.request}, app_label=data['app_label'])
  107. if data['type'] == 'children':
  108. module = index_dashboard.children[data['module']]
  109. elif data['type'] == 'available_children':
  110. module = index_dashboard.available_children[data['module']]()
  111. else:
  112. raise ValidationError('error')
  113. self.module_cls = module
  114. return data
  115. def save(self, commit=True):
  116. self.instance.title = self.module_cls.title
  117. self.instance.module = self.module_cls.fullname()
  118. self.instance.user = self.request.user.pk
  119. self.instance.column = 0
  120. self.instance.order = -1
  121. self.instance.settings = self.module_cls.dump_settings()
  122. self.instance.children = self.module_cls.dump_children()
  123. return super(AddUserDashboardModuleForm, self).save(commit)
  124. class UpdateDashboardModuleCollapseForm(forms.ModelForm):
  125. def __init__(self, request, *args, **kwargs):
  126. self.request = request
  127. super(UpdateDashboardModuleCollapseForm, self).__init__(*args, **kwargs)
  128. class Meta:
  129. model = UserDashboardModule
  130. fields = ['collapsed']
  131. def clean(self):
  132. data = super(UpdateDashboardModuleCollapseForm, self).clean()
  133. if self.instance.user != self.request.user.pk:
  134. raise ValidationError('error')
  135. return data
  136. class RemoveDashboardModuleForm(forms.ModelForm):
  137. def __init__(self, request, *args, **kwargs):
  138. self.request = request
  139. super(RemoveDashboardModuleForm, self).__init__(*args, **kwargs)
  140. class Meta:
  141. model = UserDashboardModule
  142. fields = []
  143. def clean(self):
  144. cleaned_data = super(RemoveDashboardModuleForm, self).clean()
  145. if self.instance.user != self.request.user.pk:
  146. raise ValidationError('error')
  147. return cleaned_data
  148. def save(self, commit=True):
  149. if commit:
  150. self.instance.delete()
  151. class ModelLookupForm(forms.Form):
  152. app_label = forms.CharField()
  153. model = forms.CharField()
  154. q = forms.CharField(required=False)
  155. page = forms.IntegerField(required=False)
  156. page_size = forms.IntegerField(required=False, min_value=1, max_value=1000)
  157. object_id = forms.IntegerField(required=False)
  158. model_cls = None
  159. def clean(self):
  160. data = super(ModelLookupForm, self).clean()
  161. try:
  162. self.model_cls = get_model(data['app_label'], data['model'])
  163. except:
  164. raise ValidationError('error')
  165. return data
  166. def lookup(self):
  167. qs = self.model_cls.objects
  168. if self.cleaned_data['q']:
  169. if getattr(self.model_cls, 'autocomplete_search_fields', None):
  170. search_fields = self.model_cls.autocomplete_search_fields()
  171. filter_data = [Q((field + '__icontains', self.cleaned_data['q'])) for field in search_fields]
  172. # if self.cleaned_data['object_id']:
  173. # filter_data.append(Q(pk=self.cleaned_data['object_id']))
  174. qs = qs.filter(reduce(operator.or_, filter_data))
  175. else:
  176. qs = qs.none()
  177. limit = self.cleaned_data['page_size'] or 100
  178. page = self.cleaned_data['page'] or 1
  179. offset = (page - 1) * limit
  180. items = list(map(
  181. lambda instance: {'id': instance.pk, 'text': get_model_instance_label(instance)},
  182. qs.all()[offset:offset + limit]
  183. ))
  184. total = qs.count()
  185. return items, total