Save gTTS audio on Django.

PHOTO EMBED

Thu Apr 08 2021 21:45:55 GMT+0000 (Coordinated Universal Time)

Saved by @marcoycaza #python

import tempfile

from django.core.files import File
from django.db import models


class Word(models.Model):
    word = models.CharField(max_length=200)
    audio = models.FileField(upload_to='audio/', blank=True)

    def save(self, *args, **kwargs):
        audio = gTTS(text=self.word_vocab, lang='en', slow=True)

        with tempfile.TemporaryFile(mode='w') as f:
            audio.write_to_fp(f)
            file_name = '{}.mp3'.format(self.word_vocab)
            self.audio.save(file_name, File(file=f))

        super(Word, self).save(*args, **kwargs)

#The function audio.save(self.word_vocab + ".mp3") won't work in your use case, you must use #write_to_fp or open the file created by this method, as pointed in doccumentation. I hope it helps
content_copyCOPY

https://stackoverflow.com/questions/49932332/how-to-save-audio-file-in-django-by-overriding-save-method/49932777