简体   繁体   中英

How to send dynamic data in email in Django Rest Framework

I am trying to write a function that sends a notification email after a file has been uploaded. My below code works if I hard-code the "send-to" email address.

def perform_create(self, serializer):
        serializer.save(owner=self.request.user)
        from_email = self.request.user.email
        send_mail('New Files have been Uploaded',
                  'New files have been uploaded.',
                  from_email,
                  ['sendto@email.com', ],
                  fail_silently=False)

I need to set the "sendto@email.com" dynamically based on the editor_email that is in the serializer. Below is the serializer.

class VideoSerializer(serializers.ModelSerializer):
    projectName = serializers.SerializerMethodField(allow_null=True)
    editor_email = serializers.EmailField(
        source='editor.email', required=False)

    class Meta:
        model = Video
        # fields = '__all__'
        fields = [
            'url',
            'handle',
            'filename',
            'size',
            'source',
            'uploadId',
            'originalPath',
            'owner',
            'project',
            'uploadDate',
            'editor',
            'projectName',
            'editor_email'
        ]

    def get_projectName(self, obj):
        return obj.project.projectName

When I check the JSON response in the front end of the app, the value for "editor_email" is what I expect it to be.

I am relatively new to Django Rest Framework and there must be something I am missing here. I have spent hours reading through the documentation and trying different things but nothing seems to work.

Please, can someone tell me how to set this email based on the serializer?

Remove the mail send code snippet from views.py and move it into serilizers as

# views.py
def perform_create(self, serializer):
    serializer.save(owner=self.request.user)
    


# serializers.py
class VideoSerializer(serializers.ModelSerializer):
    # your code


    

I think you could get the field editor_email data in your function. If it only string data, then you could do it like this:

def perform_create(self, serializer):
        serializer.save(owner=self.request.user)
        to_email = serializer.data['editor_email']

        if to_email:
            from_email = self.request.user.email
            send_mail('New Files have been Uploaded',
                      'New files have been uploaded.',
                      from_email,
                      [to_email, ],
                      fail_silently=False)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM