Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-viewsdjango-mailer

How to send mail to the post author when got new comment in django rest framework through serializer?


I am trying to build an API where students will ask questions and the teacher will answer that question. For asking questions and answering I am using the blog post way. Now, my problem is I am trying to send mail from the serializer. But when I want to detect the post author I am unable to do that. I can send selected users but not from the model. If anyone can help me with that it will be so helpful. Thanks a lot.

these are the add_question model and answer the question model ---

    class add_question(models.Model):
    title = models.CharField(max_length=250, blank=False)
    description = models.TextField(blank=True, null=True)
    is_answered = models.BooleanField(default=False)
    is_deleted = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE)
    STATUS = (
        ('Published', 'Published'),
        ('Suspended', 'Suspended'),
        ('Unpublished', 'Unpublished'),
    )
    status = models.CharField(choices=STATUS, default='Published', max_length=100)
    RESOLUTION = (
        ('Resolved', 'Resolved'),
        ('Unresolved', 'Unresolved'),
    )
    resolution = models.CharField(choices=RESOLUTION, default='Published', max_length=100)

    def __str__(self):
        return self.title


class add_questionFile(models.Model):
    question = models.ForeignKey(add_question, on_delete=models.CASCADE, related_name='files')
    file = models.FileField('files', upload_to=path_and_rename, max_length=500, null=True, blank=True)




class submit_answer(models.Model):
    description = models.TextField(blank=False, null=False)
    is_deleted = models.BooleanField(default=False)
    rating = models.FloatField(blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    question_id = models.ForeignKey(add_question, blank=False, on_delete=models.CASCADE)
    created_by = models.ForeignKey(User, blank=False, on_delete=models.CASCADE)

class submit_answerFile(models.Model):
    answer = models.ForeignKey(submit_answer, on_delete=models.CASCADE, related_name='files')
    file = models.FileField('files', upload_to=path_and_rename, max_length=500, null=True, blank=True)

these are the serializer

class add_questionFileSerializer(serializers.ModelSerializer):
    class Meta:
        model = add_questionFile
        fields = ['id', 'file', 'question']
        extra_kwargs = {
        'question': {'required': False},
        }

class add_questionSerializer(serializers.ModelSerializer):
    files = add_questionFileSerializer(many=True, required=False)

    class Meta:
        model = add_question
        fields = ('id', 'created_by', 'title', 'description', 'files', 'is_answered')

    def create(self, validated_data):        
        question = add_question.objects.create(**validated_data)
        try:
            # try to get and save images (if any)
            files_data = dict((self.context['request'].FILES).lists()).get('files', None)
            for file in files_data:
                add_questionFile.objects.create(question=question, file=file)
        except:
            # if no images are available - create using default image
            add_questionFile.objects.create(question=question)
        send_mail(
            'Question {} has been asked'.format(question.pk),
            'A new question has been asked . DATA: {}'.format(validated_data),
            '[email protected]',
            ['[email protected]', '[email protected]'],
            fail_silently=False,
        )
        send_mail(
            'Your question has been submitted'.format(question.pk),
            'Your asked question has been submitted to SUFLEK. We will reach with solution soon. DATA: {}'.format(validated_data),
            '[email protected]',
            ['[email protected]'],
            fail_silently=False,
        )
        return question


class submit_answerFileSerializer(serializers.ModelSerializer):
    class Meta:
        model = submit_answerFile
        fields = ['id', 'file', 'answer']
        extra_kwargs = {
        'answer': {'required': False},
        }

class submit_answerSerializer(serializers.ModelSerializer):
    files = submit_answerFileSerializer(many=True, required=False)

    class Meta:
        model = submit_answer
        fields = ('id', 'question_id', 'created_by', 'description', 'files')

    def create(self, validated_data):

        answer = submit_answer.objects.create(**validated_data)
        try:
            # try to get and save images (if any)
            files_data = dict((self.context['request'].FILES).lists()).get('files', None)
            for file in files_data:
                submit_answerFile.objects.create(answer=answer, file=file)
        except:
            # if no images are available - create using default image
            submit_answerFile.objects.create(answer=answer)
        
        send_mail(
            'Your asked question has been answered',
            'Here is the message. DATA: {}'.format(validated_data),
            '[email protected]',
            ['[email protected]'], # need to add the user who asked the question
            fail_silently=False,
        )
        return answer

these are the views

    # ask question POST and GET API
class add_questionAPIView(generics.ListCreateAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    queryset = add_question.objects.all()
    serializer_class = add_questionSerializer
    
    #single question GET API
class all_questionsDetailsAPIView(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    queryset = add_question.objects.all()
    serializer_class = add_questionSerializer

# comment POST and GET API
class submitanswerAPIView(generics.ListCreateAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    queryset = submit_answer.objects.all()
    serializer_class = submit_answerSerializer

    #single comment GET API
class submitanswerDetailsAPIView(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    queryset = submit_answer.objects.all()
    serializer_class = submit_answerSerializer

if any other information is required please let me know. I am not so expert all are doing by study. Once again thanks in advance.


Solution

  • I also solved the problem almost like the solution above. But thought to share with you all and for my future use as well.

    I just modified the serializer's send_mail() to_email part and called it through the foreign key.

    on add_question I am using two emails at one action and submit_answer one. Thanks I hope this works and help you.

    #add_questionFileSerializer
    
        send_mail(
                    'Question {} has been asked'.format(question.pk),
                    'A new question has been asked . DATA: {}'.format(validated_data),
                    '[email protected]',
                    ['[email protected]', '[email protected]'],
                    fail_silently=False,
                )
                send_mail(
                    'Your question has been submitted'.format(question.pk),
                    'Your asked question has been submitted to SUFLEK. We will reach with solution soon. DATA: {}'.format(validated_data),
                    '[email protected]',
                    # [to_email],
                    ['{}'.format(question.created_by)],
                    fail_silently=False,
                )
    
    
    #submit_answerSerializer
        send_mail(
                # subject
                'Your asked question has been answered',
                # body
                'Here is the message. DATA: {}'.format(validated_data),
                # from mail
                '[email protected]',
                # to mail
                ['{}'.format(answer.question_id.created_by)], //this line I got my solution
                fail_silently=False,
            )