Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from django.shortcuts import render
- from .tasks import send_messages
- from rest_framework.status import HTTP_400_BAD_REQUEST
- from django.shortcuts import render
- from .models import Room, Arborist, Landlord, ArboristProfile, LandlordProfile
- from arborfindr.models import User
- from rest_framework.views import APIView
- from rest_framework.decorators import authentication_classes, permission_classes
- from rest_framework_simplejwt.authentication import JWTAuthentication
- from rest_framework.response import Response
- from rest_framework.permissions import IsAuthenticated, DjangoModelPermissionsOrAnonReadOnly, AllowAny
- from django.contrib.auth import login
- from .serializers import RoomSerializer, RegisterChatSerializer, LoginChatSerializer, ArboristProfileSerializer, PropertyManagerSerializer
- from rest_framework.authtoken.models import Token
- from rest_framework import status, generics, permissions
- from rest_framework_simplejwt.tokens import RefreshToken
- from drf_haystack.viewsets import HaystackViewSet
- from haystack.query import SearchQuerySet
- from rest_framework import permissions
- from rest_framework.decorators import action
- from rest_framework.parsers import MultiPartParser, FormParser
- def arborchat_home(request):
- return render(request, 'arborchat/index.html', {
- 'channels': Room.objects.values_list('room_name', flat=True)
- })
- def index(request):
- return render(request, 'arborchat/index.html', {
- 'rooms': Room.objects.all(),
- })
- def messenger_room(request):
- room = Room.objects.first()
- return render(request, 'messenger.html', {'room': room })
- def property_manager_room(request):
- room = Room.objects.first()
- return render(request, 'property_manageer.html', {'room': room }}
- def business_room(request):
- room = Room.objects.first()
- return render (request, 'business_manager.html', {'room': room }}
- @authentication_classes([JWTAuthentication])
- def room_view(request, room_name):
- room, created = Room.objects.get_or_create(room_name=room_name)
- print('Room name is', room_name)
- return render(request, 'arborchat/messenger.html', {'room_name': room_name})
- # API endpoint for Arborist login
- @authentication_classes([JWTAuthentication])
- class ChatLoginView(APIView):
- authentication_classes = [JWTAuthentication]
- def post(self, request, *args, **kwargs):
- serializer = LoginChatSerializer(data=request.data, context={'request': request})
- serializer.is_valid(raise_exception=True)
- user = serializer.validated_data.get('user')
- if not user:
- return Response({'error': 'Invalid email/password'}, status=status.HTTP_401_UNAUTHORIZED)
- if user.role not in ('arborist', 'property_manager'):
- return Response({'error': 'Unauthorized role'}, status=status.HTTP_403_FORBIDDEN)
- login(request, user)
- refresh = RefreshToken.for_user(user)
- return Response({
- 'message': 'Successful login',
- 'access_token': str(refresh.access_token),
- 'refresh_token': str(refresh),
- }, status=status.HTTP_200_OK)
- # Now reachable
- @authentication_classes([JWTAuthentication])
- class ChatRegisterView(generics.CreateAPIView):
- queryset = User.objects.all()
- serializer_class = RegisterChatSerializer
- permission_classes = [permissions.AllowAny]
- def post(self, request, *args, **kwargs):
- serializer = RegisterChatSerializer(data=request.data, context={'request': request})
- serializer.is_valid(raise_exception=True)
- user = (serializer.
- save())
- if user.role == 'arborist':
- Arborist.objects.create(user=user)
- elif user.role == 'property_manager':
- Landlord.objects.create(user=user)
- return Response({'message': 'Successfully registered'}, status=status.HTTP_201_CREATED)
- @action(detail=False, methods=['get'])
- def me(self, request):
- self.kwargs['pk'] = request.user.pk
- return self.retrieve(request)
- def post(self, request):
- serializer = RegisterChatSerializer(data=request.data, context={'request': request})
- if serializer.is_valid():
- serializer.save()
- return Response({
- 'message': 'successfully registered', }, status=status.HTTP_201_CREATED)
- return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
- @authentication_classes([JWTAuthentication])
- class SendEmailView(APIView):
- def post(self, request, *args, **kwargs):
- subject = request.data.get('subject')
- message_body = request.data.get('message')
- to_emails = request.data.get('to_emails', [])
- if not subject or not message_body or not to_emails:
- return Response({'error': 'Missing required fields'}, status=HTTP_400_BAD_REQUEST)
- send_messages.delay(subject, message_body, to_emails)
- return Response ({'message': 'Email task qeued successfully'}, status=status.HTTP_202_ACCEPTED)
- class ArboristProfileView(APIView):
- queryset = ArboristProfile.objects.all()
- permission_classes = [IsAuthenticated]
- authentication_classes = [JWTAuthentication]
- serializer_class = ArboristProfileSerializer
- parser_classes = (MultiPartParser, FormParser)
- def create(self, request, *args, **kwargs):
- arborist_name = request.data["arborist_name"]
- arborist_location = request.data["arborist_location"]
- services_arborist = request.data["services_arborist"]
- description = request.data["description"]
- arborist_logo = request.data["arborist_logo"]
- ArboristProfile.objects.create(arborist_name = arborist_name, arborist_location = arborist_location, services_arborist = services_arborist,
- description = description, arborist_logo)
- return Response("Profile created", status=status.HTTP_200_OK)
- class PropertyManagerProfileView(APIView):
- queryset = LandlordProfile.objects.all()
- permission_classes = [IsAuthenticated]
- authentication_classes = [JWTAuthentication]
- serializer_class = PropertyManagerSerializer
- parser_classes = (MultiPartParser, FormParser)
- def create(self, request, *args, **kwargs):
- first_name = request.data["first_name"]
- last_name = request.data["last_name"]
- property_name = request.data["property_name"]
- property_location = request.data["property_location"]
- profile_pic = request.data["profile_pic"]
- LandlordProfile.objects.create(first_name = first_name, last_name = last_name, property_name = property_name,
- property_location = property_location, profile_pic = profile_pic)
- return Response("Profile created", status=status.HTTP_200_OK)
- class SearchBarView(APIView):
- model = Arborist
- permission_classes = [IsAuthenticated]
- serializer_classes = ArboristProfileSerializer
- success_url = '/'
- context_object_name = 'all_search_results'
- def get(self):
- query = self.request.GET.get('search')
- results = SearchQuerySet().filter(content=query)
- # serialize results based on models
- serialized_results = []
- for result in results:
- if result.model == 'arborist':
- serializer = ArboristProfileSerializer(result.object)
- elif result.model == 'company':
- serializer = PropertyManagerSerializer(result.object)
- else:
- continue
- serialized_results.append(serializer.data)
- return Response(serialized_results)
Advertisement
Add Comment
Please, Sign In to add comment