permissions.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. from django.contrib.contenttypes.models import ContentType
  2. from django.db.models import Q
  3. def get_permission_for_model(model, action):
  4. """
  5. Resolve the named permission for a given model (or instance) and action (e.g. view or add).
  6. :param model: A model or instance
  7. :param action: View, add, change, or delete (string)
  8. """
  9. if action not in ('view', 'add', 'change', 'delete'):
  10. raise ValueError(f"Unsupported action: {action}")
  11. return '{}.{}_{}'.format(
  12. model._meta.app_label,
  13. action,
  14. model._meta.model_name
  15. )
  16. def resolve_permission(name):
  17. """
  18. Given a permission name, return the relevant ContentType and action. For example, "dcim.view_site" returns
  19. (Site, "view").
  20. :param name: Permission name in the format <app>.<action>_<model>
  21. """
  22. app_label, codename = name.split('.')
  23. action, model_name = codename.split('_')
  24. try:
  25. content_type = ContentType.objects.get(app_label=app_label, model=model_name)
  26. except ContentType.DoesNotExist:
  27. raise ValueError(f"Unknown app/model for {name}")
  28. return content_type, action