views.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. from django.db.models import Q
  2. from rest_framework import exceptions, viewsets
  3. from organizations_ext.models import OrganizationUserRole
  4. from projects.models import Project
  5. from .models import ProjectAlert
  6. from .permissions import ProjectAlertPermission
  7. from .serializers import ProjectAlertSerializer
  8. class ProjectAlertViewSet(viewsets.ModelViewSet):
  9. queryset = ProjectAlert.objects.distinct()
  10. serializer_class = ProjectAlertSerializer
  11. permission_classes = [ProjectAlertPermission]
  12. def get_queryset(self):
  13. if not self.request.user.is_authenticated:
  14. return self.queryset.none()
  15. return self.queryset.filter(
  16. project__slug=self.kwargs.get("project_slug"),
  17. project__organization__users=self.request.user,
  18. project__organization__slug=self.kwargs.get("organization_slug"),
  19. )
  20. def perform_create(self, serializer):
  21. try:
  22. project = (
  23. Project.objects.distinct()
  24. .filter(
  25. Q(
  26. organization__users=self.request.user,
  27. organization__organization_users__role__gte=OrganizationUserRole.ADMIN,
  28. )
  29. | Q(team__members__user=self.request.user)
  30. )
  31. .get(
  32. slug=self.kwargs.get("project_slug"),
  33. organization__slug=self.kwargs.get("organization_slug"),
  34. )
  35. )
  36. except Project.DoesNotExist as err:
  37. raise exceptions.ValidationError("Project does not exist") from err
  38. serializer.save(project=project)