views.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. from django.contrib import messages
  2. from django.core.exceptions import ValidationError
  3. try:
  4. from django.core.urlresolvers import reverse
  5. except ImportError: # Django 1.11
  6. from django.urls import reverse
  7. from django.forms.formsets import formset_factory
  8. from django.http import HttpResponseRedirect
  9. from django.views.decorators.http import require_POST, require_GET
  10. from jet.dashboard.forms import UpdateDashboardModulesForm, AddUserDashboardModuleForm, \
  11. UpdateDashboardModuleCollapseForm, RemoveDashboardModuleForm, ResetDashboardForm
  12. from jet.dashboard.models import UserDashboardModule
  13. from jet.utils import JsonResponse, get_app_list, SuccessMessageMixin, user_is_authenticated
  14. from django.views.generic import UpdateView
  15. from django.utils.translation import ugettext_lazy as _
  16. class UpdateDashboardModuleView(SuccessMessageMixin, UpdateView):
  17. model = UserDashboardModule
  18. fields = ('title',)
  19. template_name = 'jet.dashboard/update_module.html'
  20. success_message = _('Widget was successfully updated')
  21. object = None
  22. module = None
  23. def has_permission(self, request):
  24. return request.user.is_active and request.user.is_staff
  25. def get_success_url(self):
  26. if self.object.app_label:
  27. return reverse('admin:app_list', kwargs={'app_label': self.object.app_label})
  28. else:
  29. return reverse('admin:index')
  30. def get_module(self):
  31. object = self.object if getattr(self, 'object', None) is not None else self.get_object()
  32. return object.load_module()
  33. def get_settings_form_kwargs(self):
  34. kwargs = {
  35. 'initial': self.module.settings
  36. }
  37. if self.request.method in ('POST', 'PUT'):
  38. kwargs.update({
  39. 'data': self.request.POST,
  40. 'files': self.request.FILES,
  41. })
  42. return kwargs
  43. def get_settings_form(self):
  44. if self.module.settings_form:
  45. form = self.module.settings_form(**self.get_settings_form_kwargs())
  46. if hasattr(form, 'set_module'):
  47. form.set_module(self.module)
  48. return form
  49. def get_children_formset_kwargs(self):
  50. kwargs = {
  51. 'initial': self.module.children,
  52. 'prefix': 'children',
  53. }
  54. if self.request.method in ('POST', 'PUT'):
  55. kwargs.update({
  56. 'data': self.request.POST,
  57. 'files': self.request.FILES,
  58. })
  59. return kwargs
  60. def get_children_formset(self):
  61. if self.module.child_form:
  62. return formset_factory(self.module.child_form, can_delete=True, extra=1)(**self.get_children_formset_kwargs())
  63. def clean_children_data(self, children):
  64. children = list(filter(
  65. lambda item: isinstance(item, dict) and item and item.get('DELETE') is not True,
  66. children
  67. ))
  68. for item in children:
  69. item.pop('DELETE')
  70. return children
  71. def get_current_app(self):
  72. app_list = get_app_list({'request': self.request})
  73. for app in app_list:
  74. if app.get('app_label', app.get('name')) == self.object.app_label:
  75. return app
  76. def get_context_data(self, **kwargs):
  77. data = super(UpdateDashboardModuleView, self).get_context_data(**kwargs)
  78. data['title'] = _('Change')
  79. data['module'] = self.module
  80. data['settings_form'] = self.get_settings_form()
  81. data['children_formset'] = self.get_children_formset()
  82. data['child_name'] = self.module.child_name if self.module.child_name else _('Items')
  83. data['child_name_plural'] = self.module.child_name_plural if self.module.child_name_plural else _('Items')
  84. data['app'] = self.get_current_app()
  85. return data
  86. def dispatch(self, request, *args, **kwargs):
  87. if not self.has_permission(request):
  88. index_path = reverse('admin:index')
  89. return HttpResponseRedirect(index_path)
  90. self.object = self.get_object()
  91. self.module = self.get_module()(model=self.object)
  92. return super(UpdateDashboardModuleView, self).dispatch(request, *args, **kwargs)
  93. def post(self, request, *args, **kwargs):
  94. settings_form = self.get_settings_form()
  95. children_formset = self.get_children_formset()
  96. data = request.POST.copy()
  97. if settings_form:
  98. if settings_form.is_valid():
  99. settings = settings_form.cleaned_data
  100. data['settings'] = self.module.dump_settings(settings)
  101. else:
  102. return self.form_invalid(self.get_form(self.get_form_class()))
  103. if children_formset:
  104. if children_formset.is_valid():
  105. self.module.children = self.clean_children_data(children_formset.cleaned_data)
  106. data['children'] = self.module.dump_children()
  107. else:
  108. return self.form_invalid(self.get_form(self.get_form_class()))
  109. request.POST = data
  110. return super(UpdateDashboardModuleView, self).post(request, *args, **kwargs)
  111. def form_valid(self, form):
  112. if 'settings' in form.data:
  113. form.instance.settings = form.data['settings']
  114. if 'children' in form.data:
  115. form.instance.children = form.data['children']
  116. return super(UpdateDashboardModuleView, self).form_valid(form)
  117. @require_POST
  118. def update_dashboard_modules_view(request):
  119. result = {'error': False}
  120. form = UpdateDashboardModulesForm(request, request.POST)
  121. if form.is_valid():
  122. form.save()
  123. else:
  124. result['error'] = True
  125. return JsonResponse(result)
  126. @require_POST
  127. def add_user_dashboard_module_view(request):
  128. result = {'error': False}
  129. form = AddUserDashboardModuleForm(request, request.POST)
  130. if form.is_valid():
  131. module = form.save()
  132. result['id'] = module.pk
  133. messages.success(request, _('Widget has been successfully added'))
  134. if module.app_label:
  135. result['success_url'] = reverse('admin:app_list', kwargs={'app_label': module.app_label})
  136. else:
  137. result['success_url'] = reverse('admin:index')
  138. else:
  139. result['error'] = True
  140. return JsonResponse(result)
  141. @require_POST
  142. def update_dashboard_module_collapse_view(request):
  143. result = {'error': False}
  144. try:
  145. instance = UserDashboardModule.objects.get(pk=request.POST.get('id'))
  146. form = UpdateDashboardModuleCollapseForm(request, request.POST, instance=instance)
  147. if form.is_valid():
  148. module = form.save()
  149. result['collapsed'] = module.collapsed
  150. else:
  151. result['error'] = True
  152. except UserDashboardModule.DoesNotExist:
  153. result['error'] = True
  154. return JsonResponse(result)
  155. @require_POST
  156. def remove_dashboard_module_view(request):
  157. result = {'error': False}
  158. try:
  159. instance = UserDashboardModule.objects.get(pk=request.POST.get('id'))
  160. form = RemoveDashboardModuleForm(request, request.POST, instance=instance)
  161. if form.is_valid():
  162. form.save()
  163. else:
  164. result['error'] = True
  165. except UserDashboardModule.DoesNotExist:
  166. result['error'] = True
  167. return JsonResponse(result)
  168. @require_GET
  169. def load_dashboard_module_view(request, pk):
  170. result = {'error': False}
  171. try:
  172. if not user_is_authenticated(request.user) or not request.user.is_staff:
  173. raise ValidationError('error')
  174. instance = UserDashboardModule.objects.get(pk=pk, user=request.user.pk)
  175. module_cls = instance.load_module()
  176. module = module_cls(model=instance, context={'request': request})
  177. result['html'] = module.render()
  178. except (ValidationError, UserDashboardModule.DoesNotExist):
  179. result['error'] = True
  180. return JsonResponse(result)
  181. @require_POST
  182. def reset_dashboard_view(request):
  183. result = {'error': False}
  184. form = ResetDashboardForm(request, request.POST)
  185. if form.is_valid():
  186. form.save()
  187. else:
  188. result['error'] = True
  189. return JsonResponse(result)