我有以下型号:
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
在我的视图中,我正在录制来自用户的音频文件,如下所示:
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
我的MEDIA_ROOT定义如下:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_in_env", "media_root")
所以在这个media_root文件夹中,我必须创建一个带有用户名的文件夹,然后将文件保存在其中。我创建了upload_to函数来保存我的文件。
我做了以下事情:
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"
但它没有保存任何东西。
2)user_audio_answer.audio_file = settings.MEDIA_ROOT+"/"+request.user.username+"/"+random_file_name+".flac"
它会保存文件的路径,但路径从/ Users / username / desktop开始,然后继续。
将文件保存到后端的正确方法是什么,我正在这样做?