Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

generic.py 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from django.utils.encoding import smart_str
  2. from django.core.urlresolvers import reverse
  3. from django.contrib import messages
  4. from django.http import HttpResponseRedirect
  5. class PostActionMixin(object):
  6. """
  7. Simple mixin to forward POST request that contain a key 'action'
  8. onto a method of form "do_{action}".
  9. This only works with DetailView
  10. """
  11. def post(self, request, *args, **kwargs):
  12. if 'action' in self.request.POST:
  13. model = self.get_object()
  14. # The do_* method is required to do what it needs to with the model
  15. # it is passed, and then to assign the HTTP response to self.response.
  16. method_name = "do_%s" % self.request.POST['action'].lower()
  17. if hasattr(self, method_name):
  18. getattr(self, method_name)(model)
  19. return self.response
  20. else:
  21. messages.error(request, "Invalid form submission")
  22. return super(PostActionMixin, self).post(request, *args, **kwargs)
  23. class BulkEditMixin(object):
  24. """
  25. Mixin for views that have a bulk editing facility. This is normally in the
  26. form of tabular data where each row has a checkbox. The UI allows a number
  27. of rows to be selected and then some 'action' to be performed on them.
  28. """
  29. actions = None
  30. current_view = None
  31. checkbox_object_name = None
  32. def get_checkbox_object_name(self):
  33. object_list = self.get_queryset()
  34. if self.checkbox_object_name:
  35. return self.checkbox_object_name
  36. elif hasattr(object_list, 'model'):
  37. return smart_str(object_list.model._meta.object_name.lower())
  38. else:
  39. return None
  40. def post(self, request, *args, **kwargs):
  41. # Dynamic dispatch patter - we forward POST requests onto a method
  42. # designated by the 'action' parameter. The action has to be in a
  43. # whitelist to avoid security issues.
  44. action = request.POST.get('action', '').lower()
  45. if not self.actions or action not in self.actions:
  46. messages.error(self.request, "Invalid action")
  47. return HttpResponseRedirect(reverse(self.current_view))
  48. ids = request.POST.getlist('selected_%s' % self.get_checkbox_object_name())
  49. if not ids:
  50. messages.error(self.request, "You need to select some %ss" % self.get_checkbox_object_name())
  51. return HttpResponseRedirect(reverse(self.current_view))
  52. raw_objects = self.model.objects.in_bulk(ids)
  53. objects = (raw_objects[int(id)] for id in ids)
  54. return getattr(self, action)(request, objects)