views.py 7.6 KB

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