Как отправить по почте пользователю файл pdf, хранящийся в базе данных в папке media -Django

У меня есть модель, которая хранит некоторые pdf файлы. Я хочу отправлять pdf-файл в качестве вложения, когда пользователь просит об этом. Я пробовал сделать это следующим образом

@api_view(['POST'])
def send_pdf_to_user(request):
    
    id = request.data.get('id')
    
    try:
        query = Civil.objects.get(id=id)
        
        file = query.pdf_file
        
        email = EmailMessage(
        'Subject here', 'Here is the message.', 'from@me.com', ['user@gmail.com'])
        email.attach_file(file)
        email.send()
        
        return Response(status=200)
    except Exception as e:
      print(e)
      
      return Response({str(e)}, status=400)

но получил эту ошибку

expected str, bytes or os.PathLike object, not FieldFile

При печати file выдает следующее - путь, по которому хранится файл

civil/random.pdf

Пожалуйста, подскажите мне способ отправки по почте pdf-файлов, предварительно сохраненных в базе данных.

После того, как возникло исключение, я заметил, что email.attach() запрашивал строковый тип, а ему было передано поле file. Также требовался полный путь к файлу, а не просто civil/random.pdf. Итак, я воспользовался комментарием Art выше и написал следующий код, и теперь он работает.

@api_view(['POST'])
def send_pdf_to_user(request):
    
    id = request.data.get('id')
    
    try:
        query = Civil.objects.get(id=id)
        
        file = query.pdf_file.file # Art suggested this
        
        print(f'\nThis is the file {file}\n')
        
        email = EmailMessage(
        'Subject here', 'Here is the message.', 'from@me.com', ['user@gmail.com'])
        email.attach_file(str(file)) # converted the file path to str
        email.send()
        
        return Response(status=200)
    except Exception as e:
      print("this is the exception",e)
      
      return Response({str(e)}, status=400)
Вернуться на верх