Spaces:
Running
Running
Download api/views_projects.py from Dayozoe/harvestconnect-api: direct link, hf CLI and curl.
- Browser
- Download file 1.98 kB
-
https://huggingface.co/spaces/Dayozoe/harvestconnect-api/resolve/main/api/views_projects.py
- Command line
-
hf download hf://spaces/Dayozoe/harvestconnect-api/api/views_projects.py
-
curl -L -o views_projects.py https://huggingface.co/spaces/Dayozoe/harvestconnect-api/resolve/main/api/views_projects.py
1.98 kB
| from django.db import models | |
| from rest_framework import filters, viewsets, permissions | |
| from rest_framework.exceptions import ValidationError | |
| from django_filters.rest_framework import DjangoFilterBackend | |
| from .models import Project, UserProfile | |
| from .serializers import ProjectSerializer | |
| class ProjectViewSet(viewsets.ModelViewSet): | |
| """Project engagements visible to their client, assigned tradesman, or an admin.""" | |
| serializer_class = ProjectSerializer | |
| permission_classes = [permissions.IsAuthenticated] | |
| filter_backends = [DjangoFilterBackend, filters.OrderingFilter] | |
| filterset_fields = ['status', 'tradesman', 'client'] | |
| ordering = ['-created_at'] | |
| def _user_role(self): | |
| # A user can exist without an extended profile (legacy/imported accounts). | |
| return UserProfile.objects.filter(user=self.request.user).values_list('role', flat=True).first() or '' | |
| def get_queryset(self): | |
| user = self.request.user | |
| if user.is_staff or self._user_role() == 'admin': | |
| return Project.objects.all().order_by('-created_at') | |
| # Never fall back to all projects when the user has no matching records. | |
| return Project.objects.filter( | |
| models.Q(tradesman=user) | models.Q(client=user) | |
| ).order_by('-created_at') | |
| def perform_create(self, serializer): | |
| user = self.request.user | |
| role = self._user_role() | |
| if role in ['tradesman', 'artisan']: | |
| # A tradesman can only create projects under their own account. | |
| serializer.save(tradesman=user) | |
| return | |
| # Clients must select the tradesman they are requesting work from. | |
| if not serializer.validated_data.get('tradesman'): | |
| raise ValidationError({ | |
| 'tradesman_id': 'Choose the tradesman or artisan for this project.' | |
| }) | |
| # Never allow a client to create a project on behalf of another client. | |
| serializer.save(client=user) | |