actions.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from django import forms
  2. from django.apps import apps
  3. __all__ = (
  4. 'RegisteredActionsWidget',
  5. )
  6. class RegisteredActionsWidget(forms.CheckboxSelectMultiple):
  7. """
  8. Widget rendering checkboxes for registered model actions.
  9. Groups actions by model with data attributes for JS show/hide.
  10. """
  11. template_name = 'widgets/registered_actions.html'
  12. def __init__(self, *args, model_actions=None, **kwargs):
  13. super().__init__(*args, **kwargs)
  14. self.model_actions = model_actions or {}
  15. def get_context(self, name, value, attrs):
  16. context = super().get_context(name, value, attrs)
  17. # Build model_actions with labels for v2 template
  18. model_actions_with_labels = {}
  19. for model_key, actions in self.model_actions.items():
  20. app_label, model_name = model_key.split('.')
  21. try:
  22. model = apps.get_model(app_label, model_name)
  23. app_config = apps.get_app_config(app_label)
  24. label = f"{app_config.verbose_name} | {model._meta.verbose_name.title()}"
  25. except LookupError:
  26. label = model_key
  27. model_actions_with_labels[model_key] = {
  28. 'label': label,
  29. 'actions': actions,
  30. }
  31. context['widget']['model_actions'] = model_actions_with_labels
  32. context['widget']['value'] = value or []
  33. return context