Set Django's FileField to an existing file Set Django's FileField to an existing file django django

Set Django's FileField to an existing file


just set instance.field.name to the path of your file

e.g.

class Document(models.Model):    file = FileField(upload_to=get_document_path)    description = CharField(max_length=100)doc = Document()doc.file.name = 'path/to/file'  # must be relative to MEDIA_ROOTdoc.file<FieldFile: path/to/file>


If you want to do this permanently, you need to create your own FileStorage class

import osfrom django.conf import settingsfrom django.core.files.storage import FileSystemStorageclass MyFileStorage(FileSystemStorage):    # This method is actually defined in Storage    def get_available_name(self, name):        if self.exists(name):            os.remove(os.path.join(settings.MEDIA_ROOT, name))        return name # simply returns the name passed

Now in your model, you use your modified MyFileStorage

from mystuff.customs import MyFileStoragemfs = MyFileStorage()class SomeModel(model.Model):   my_file = model.FileField(storage=mfs)


try this (doc):

instance.field.name = <PATH RELATIVE TO MEDIA_ROOT> instance.save()