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.

54 lines
2.1 KiB

3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
  1. from django.shortcuts import get_object_or_404
  2. from django_filters.rest_framework import DjangoFilterBackend
  3. from rest_framework import filters, generics, status
  4. from rest_framework.permissions import IsAuthenticated
  5. from rest_framework.response import Response
  6. from examples.filters import ExampleFilter
  7. from examples.models import Example
  8. from examples.serializers import ExampleSerializer
  9. from projects.models import Member, Project
  10. from projects.permissions import IsProjectAdmin, IsProjectStaffAndReadOnly
  11. class ExampleList(generics.ListCreateAPIView):
  12. serializer_class = ExampleSerializer
  13. permission_classes = [IsAuthenticated & (IsProjectAdmin | IsProjectStaffAndReadOnly)]
  14. filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
  15. ordering_fields = ("created_at", "updated_at", "score")
  16. search_fields = ("text", "filename")
  17. model = Example
  18. filterset_class = ExampleFilter
  19. @property
  20. def project(self):
  21. return get_object_or_404(Project, pk=self.kwargs["project_id"])
  22. def get_queryset(self):
  23. member = get_object_or_404(Member, project=self.project, user=self.request.user)
  24. if member.is_admin():
  25. return self.model.objects.filter(project=self.project)
  26. queryset = self.model.objects.filter(project=self.project, assignments__assignee=self.request.user)
  27. if self.project.random_order:
  28. queryset = queryset.order_by("assignments__id")
  29. return queryset
  30. def perform_create(self, serializer):
  31. serializer.save(project=self.project)
  32. def delete(self, request, *args, **kwargs):
  33. queryset = self.project.examples
  34. delete_ids = request.data["ids"]
  35. if delete_ids:
  36. queryset.filter(pk__in=delete_ids).delete()
  37. else:
  38. queryset.all().delete()
  39. return Response(status=status.HTTP_204_NO_CONTENT)
  40. class ExampleDetail(generics.RetrieveUpdateDestroyAPIView):
  41. queryset = Example.objects.all()
  42. serializer_class = ExampleSerializer
  43. lookup_url_kwarg = "example_id"
  44. permission_classes = [IsAuthenticated & (IsProjectAdmin | IsProjectStaffAndReadOnly)]