2023-06-28 00:49:11 +08:00
|
|
|
from django.shortcuts import render
|
|
|
|
from .models import Message
|
|
|
|
from .serializers import MessageSerializer
|
|
|
|
from rest_framework.permissions import IsAuthenticated
|
|
|
|
from rest_framework.exceptions import PermissionDenied
|
|
|
|
from rest_framework import viewsets
|
|
|
|
from student_status.models import StudentStatus
|
2023-06-28 01:18:37 +08:00
|
|
|
from rest_framework.response import Response
|
|
|
|
from rest_framework import status
|
2023-06-28 00:49:11 +08:00
|
|
|
# Create your views here.
|
|
|
|
|
|
|
|
|
|
|
|
class MessageViewSet(viewsets.ModelViewSet):
|
|
|
|
serializer_class = MessageSerializer
|
|
|
|
permission_classes = [IsAuthenticated]
|
2023-06-28 01:18:37 +08:00
|
|
|
http_method_names = ['get', 'post']
|
2023-09-25 21:09:31 +08:00
|
|
|
queryset = Message.objects.all()
|
2023-06-28 00:49:11 +08:00
|
|
|
|
2023-06-28 01:18:37 +08:00
|
|
|
def perform_create(self, serializer):
|
|
|
|
user = self.request.user
|
2023-09-25 21:09:31 +08:00
|
|
|
user_status = StudentStatus.objects.filter(user=user).first()
|
|
|
|
user_study_group = user_status.study_group
|
|
|
|
serializer.save(user=user, study_group=user_study_group)
|
2023-06-28 01:18:37 +08:00
|
|
|
|
2023-06-28 00:49:11 +08:00
|
|
|
def get_queryset(self):
|
|
|
|
user = self.request.user
|
2023-09-25 21:09:31 +08:00
|
|
|
user_status = StudentStatus.objects.filter(user=user).first()
|
|
|
|
user_study_group = user_status.study_group
|
2023-06-28 00:49:11 +08:00
|
|
|
|
|
|
|
if not user.is_student:
|
|
|
|
raise PermissionDenied(
|
|
|
|
"You must be a student to view messages of your current study group"
|
|
|
|
)
|
|
|
|
|
2023-09-25 21:09:31 +08:00
|
|
|
if not user_study_group:
|
|
|
|
raise PermissionDenied(
|
|
|
|
"You are currently do not have a study group"
|
|
|
|
)
|
|
|
|
|
2023-06-28 00:49:11 +08:00
|
|
|
# Get student_status id of the current user
|
|
|
|
student_status = StudentStatus.objects.filter(
|
|
|
|
user=user.id
|
|
|
|
).values_list('study_group', flat=True).first()
|
|
|
|
|
|
|
|
print("User ID:", user.id)
|
|
|
|
print("Student_Status ID:", student_status)
|
2023-09-25 21:09:31 +08:00
|
|
|
print("User Study Group:", user_study_group)
|
2023-06-28 00:49:11 +08:00
|
|
|
|
|
|
|
# Now fetch the Messages matching the study group id
|
2023-06-28 01:18:37 +08:00
|
|
|
messages = Message.objects.filter(
|
2023-10-01 01:24:58 +08:00
|
|
|
study_group=user_study_group).order_by('timestamp')
|
2023-06-28 00:49:11 +08:00
|
|
|
return messages
|