I have the following model :
def upload_to(instance, filename):
return os.path.join('/%s/' % instance.user.username, filename)
class UserAudioAnswer(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
question = models.ForeignKey(Question)
audio_file = models.FileField(upload_to=upload_to)
translated_english_answer = models.TextField(null=True, blank=True)
my_points = models.IntegerField(default=-1)
def __unicode__(self):
return self.question.text
Inside my view I am recording an audio file from the user as follows:
def start_recording(r,request):
print("Reached start recording metho. About to start recording")
with sr.Microphone() as source:
print("Say something!")
audio = r.record(source,duration=5)
return audio
My MEDIA_ROOT is defined as below:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_in_env", "media_root")
So in this media_root folder I have to create a folder with the user name and then save the file inside it. I created the upload_to function to save my file there.
I have done the following:
1)
user_audio_answer = UserAudioAnswer()
user_audio_answer.audio_file.save = (random_file_name,File(f))
user_audio_answer.audio_file = settings.MEDIA_ROOT+"/"+request.user.username+"/"+random_file_name+".flac"
but it does not save anything.
2) user_audio_answer.audio_file = settings.MEDIA_ROOT+"/"+request.user.username+"/"+random_file_name+".flac"
It saves the path of the file but the path starts from /Users/username/desktop and it goes on.
What is the correct way to save the file to my backend, the way I am doing it?`