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.

52 lines
2.0 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_filters.rest_framework import DjangoFilterBackend
  3. from rest_framework import filters, generics, status
  4. from rest_framework.permissions import IsAdminUser, IsAuthenticated
  5. from rest_framework.response import Response
  6. from projects.models import Project
  7. from projects.permissions import IsProjectAdmin, IsProjectStaffAndReadOnly
  8. from projects.serializers import ProjectPolymorphicSerializer
  9. class ProjectList(generics.ListCreateAPIView):
  10. serializer_class = ProjectPolymorphicSerializer
  11. filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
  12. search_fields = ("name", "description")
  13. def get_permissions(self):
  14. if self.request.method == "GET":
  15. self.permission_classes = [
  16. IsAuthenticated,
  17. ]
  18. else:
  19. self.permission_classes = [IsAuthenticated & IsAdminUser]
  20. return super().get_permissions()
  21. def get_queryset(self):
  22. return Project.objects.filter(role_mappings__user=self.request.user)
  23. def perform_create(self, serializer):
  24. project = serializer.save(created_by=self.request.user)
  25. project.add_admin()
  26. def delete(self, request, *args, **kwargs):
  27. delete_ids = request.data["ids"]
  28. projects = Project.objects.filter(
  29. role_mappings__user=self.request.user,
  30. role_mappings__role__name=settings.ROLE_PROJECT_ADMIN,
  31. pk__in=delete_ids,
  32. )
  33. # Todo: I want to use bulk delete.
  34. # But it causes the constraint error.
  35. # See https://github.com/django-polymorphic/django-polymorphic/issues/229
  36. for project in projects:
  37. project.delete()
  38. return Response(status=status.HTTP_204_NO_CONTENT)
  39. class ProjectDetail(generics.RetrieveUpdateDestroyAPIView):
  40. queryset = Project.objects.all()
  41. serializer_class = ProjectPolymorphicSerializer
  42. lookup_url_kwarg = "project_id"
  43. permission_classes = [IsAuthenticated & (IsProjectAdmin | IsProjectStaffAndReadOnly)]