From 11d6887af8c56fdb091a187e409dd2cbcc538412 Mon Sep 17 00:00:00 2001 From: Keannu Bernasol Date: Tue, 27 Jun 2023 22:57:37 +0800 Subject: [PATCH] Polished study_groups list view to only show study_groups which are the same course as the user requesting --- stude/api/urls.py | 3 ++- stude/study_groups/urls.py | 7 +++++++ stude/study_groups/views.py | 26 ++++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/stude/api/urls.py b/stude/api/urls.py index 92865d0..f0d7631 100644 --- a/stude/api/urls.py +++ b/stude/api/urls.py @@ -7,5 +7,6 @@ urlpatterns = [ path('courses/', include('courses.urls')), path('year_levels/', include('year_levels.urls')), path('semesters/', include('semesters.urls')), - path('subjects/', include('subjects.urls')) + path('subjects/', include('subjects.urls')), + path('study_groups/', include('study_groups.urls')) ] diff --git a/stude/study_groups/urls.py b/stude/study_groups/urls.py index e69de29..f8ea1f6 100644 --- a/stude/study_groups/urls.py +++ b/stude/study_groups/urls.py @@ -0,0 +1,7 @@ +from django.urls import include, path +from .views import StudyGroupListView, StudyGroupMembershipViewSet + +urlpatterns = [ + path('', StudyGroupListView.as_view()), + path('membership/', StudyGroupMembershipViewSet.as_view()), +] diff --git a/stude/study_groups/views.py b/stude/study_groups/views.py index 265a611..6c37c9f 100644 --- a/stude/study_groups/views.py +++ b/stude/study_groups/views.py @@ -1,14 +1,40 @@ from django.shortcuts import render from rest_framework import generics +from rest_framework.exceptions import PermissionDenied +from rest_framework.permissions import IsAuthenticated from .serializers import StudyGroupSerializer from .models import StudyGroup +from courses.models import SubjectCourse # Create your views here. class StudyGroupListView(generics.ListAPIView): + permission_classes = [IsAuthenticated] serializer_class = StudyGroupSerializer queryset = StudyGroup.objects.all() + def get_queryset(self): + user = self.request.user + + if not user.is_student: + raise PermissionDenied( + "You must be a student to view study groups" + ) + + # Get the user's course + user_course = user.course + print(user_course) + # Get subject ids related to the user's course through SubjectCourse + subject_ids = SubjectCourse.objects.filter( + course=user_course + ).values_list('subject', flat=True) + + print(subject_ids) + + # Now fetch the StudyGroups with the subjects from the obtained subject_ids + studygroups = StudyGroup.objects.filter(subject_id__in=subject_ids) + return studygroups + class StudyGroupMembershipViewSet(generics.ListAPIView): serializer_class = StudyGroupSerializer