import logging from django.shortcuts import render from django.core import serializers from django.core.mail import EmailMessage from django.template.loader import render_to_string # Create your views here. from rest_framework import viewsets from rest_framework.response import Response from rest_framework.permissions import IsAuthenticatedOrReadOnly, IsAuthenticated from rest_framework.decorators import api_view, permission_classes, action from companies.models import Company from companies.serializers import CompanySerializer from back_latienda.permissions import IsCreator class CompanyViewSet(viewsets.ModelViewSet): queryset = Company.objects.all() serializer_class = CompanySerializer permission_classes = [IsAuthenticatedOrReadOnly, IsCreator] def perform_create(self, serializer): serializer.save(creator=self.request.user) @action(detail=True, methods=['POST', ]) def email_manager(self, request, **kwargs): """ Send email to company.creator """ queryset = self.get_custom_queryset(request) instance = queryset.filter(pk=kwargs['pk']).first() if instance: data = json.loads(request.body) # send email to manager message = render_to_string('company_contact.html', { 'user': request.user, 'data': data, }) email = EmailMessage(subject, message, to=[instance.creator.email]) email.send() logging.info(f"Email sent to {instance.creator.email} as manager of {instance.name}") # send confirmation email to user message = render_to_string('confirm_company_contact.html', { 'user': request.user, }) email = EmailMessage(subject, message, to=[request.user.email]) email.send() logging.info(f"Confirmation email sent to {request.user.email}") return Response(data=data) else: return Response({"errors":{"details": f"No instance of company with id {kwargs['pk']}",}}) @api_view(['GET',]) @permission_classes([IsAuthenticated,]) def my_company(request): qs = Company.objects.filter(creator=request.user) data = serializers.serialize('json', qs) return Response(data=data)