Kumar
Kumar

Reputation: 93

Django Create file in MEDIA_ROOT folder and save it to FileField

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",

Upvotes: 3

Views: 2232

Answers (1)

Kumar
Kumar

Reputation: 93

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.

Upvotes: 2

Related Questions