You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.6 KiB

3 years ago
2 years ago
3 years ago
2 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
2 years ago
3 years ago
2 years ago
  1. from django.conf import settings
  2. from django.db import transaction
  3. from django.shortcuts import get_object_or_404
  4. from django_filters.rest_framework import DjangoFilterBackend
  5. from rest_framework import filters, generics, status, views
  6. from rest_framework.permissions import IsAdminUser, IsAuthenticated
  7. from rest_framework.response import Response
  8. from projects.models import Project
  9. from projects.permissions import IsProjectAdmin, IsProjectStaffAndReadOnly
  10. from projects.serializers import ProjectPolymorphicSerializer
  11. class ProjectList(generics.ListCreateAPIView):
  12. serializer_class = ProjectPolymorphicSerializer
  13. filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
  14. search_fields = ("name", "description")
  15. ordering_fields = ["name", "created_at", "created_by", "project_type"]
  16. ordering = ["-created_at"]
  17. def get_permissions(self):
  18. if self.request.method == "GET":
  19. self.permission_classes = [
  20. IsAuthenticated,
  21. ]
  22. else:
  23. self.permission_classes = [IsAuthenticated & IsAdminUser]
  24. return super().get_permissions()
  25. def get_queryset(self):
  26. return Project.objects.filter(role_mappings__user=self.request.user)
  27. def perform_create(self, serializer):
  28. project = serializer.save(created_by=self.request.user)
  29. project.add_admin()
  30. def delete(self, request, *args, **kwargs):
  31. delete_ids = request.data["ids"]
  32. projects = Project.objects.filter(
  33. role_mappings__user=self.request.user,
  34. role_mappings__role__name=settings.ROLE_PROJECT_ADMIN,
  35. pk__in=delete_ids,
  36. )
  37. # Todo: I want to use bulk delete.
  38. # But it causes the constraint error.
  39. # See https://github.com/django-polymorphic/django-polymorphic/issues/229
  40. for project in projects:
  41. project.delete()
  42. return Response(status=status.HTTP_204_NO_CONTENT)
  43. class ProjectDetail(generics.RetrieveUpdateDestroyAPIView):
  44. queryset = Project.objects.all()
  45. serializer_class = ProjectPolymorphicSerializer
  46. lookup_url_kwarg = "project_id"
  47. permission_classes = [IsAuthenticated & (IsProjectAdmin | IsProjectStaffAndReadOnly)]
  48. class CloneProject(views.APIView):
  49. permission_classes = [IsAuthenticated & IsProjectAdmin]
  50. @transaction.atomic
  51. def post(self, request, *args, **kwargs):
  52. project = get_object_or_404(Project, pk=self.kwargs["project_id"])
  53. cloned_project = project.clone()
  54. serializer = ProjectPolymorphicSerializer(cloned_project)
  55. return Response(serializer.data, status=status.HTTP_201_CREATED)