3

Currently I want to create a file under MEDIA_ROOT folder and save it to FileField. I searched on SO website, tried the method on django-how-to-create-a-file-and-save-it-to-a-models-filefield and other, but looks it saved absolute path on my db.

My Model

class Voice(models.Model):
    xxx other field
    textFile = models.FileField(null=True,blank=True,default=None,upload_to='text_file', unique=True)

Update textFile field as following:

@receiver(post_save, sender=Voice)
def create_text(sender,**kwargs):
    xxx
    f = open(settings.MEDIA_ROOT + '/text_file/'+ text_file,'w')
    queryset = Voice.objects.all()
    queryset.filter(pk=voice.pk).update(textFile=File(f))
    f.close()

And I find it save something like this on db: "textFile": "http://127.0.0.1:8000/media/Users/usersxxx/Documents/xxx/media/text_file/t5"

while not:

"http://127.0.0.1:8000/media/text_file/t5",

Kumar
  • 73
  • 7
  • What is the value of `settings.MEDIA_ROOT` ? – JPG Sep 20 '20 at 03:23
  • Its: "Users/usersxxx/Documents/xxx/media" ; If i set relative path directly, seems python cannot open relative file directly, it will report error like"FileNotFoundError: [Errno 2] No such file or directory" – Kumar Sep 20 '20 at 03:30

1 Answers1

1

Solved this issue. The root cause of the issue due to python cannot open file with relative path. So we can solve this issue in two steps.

  1. Open file from absolute path as below(use absolute path)
    f = open(settings.MEDIA_ROOT + '/text_file/'+ text_file + '.txt','w')
    f.close()
    
  2. then update/save file(use relative path)
    queryset.filter(pk=voice.pk).update(textFile='text_file/' + text_file + '.txt')
    

Hope can help someone who hit similar question.

Kumar
  • 73
  • 7