I have an existing file on disk (say /folder/file.txt) and a FileField model field in Django.
When I do
instance.field = File(file('/folder/file.txt')) instance.save()
it re-saves the file as file_1.txt
(the next time it's _2
, etc.).
I understand why, but I don't want this behavior - I know the file I want the field to be associated with is really there waiting for me, and I just want Django to point to it.
How?
You want to have a look at FileField and FieldFile in the Django docs, and especially FieldFile. save(). where new_name is the filename you wish assigned and new_contents is the content of the file. Note that new_contents must be an instance of either django.
By default, Django stores files locally, using the MEDIA_ROOT and MEDIA_URL settings. The examples below assume that you're using these defaults. However, Django provides ways to write custom file storage systems that allow you to completely customize where and how Django stores files.
In Django, a default database is automatically created for you. All you have to do is add the tables called models. The upload_to tells Django to store the photo in a directory called pics under the media directory. The list_display list tells Django admin to display its contents in the admin dashboard.
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_ROOT doc.file <FieldFile: path/to/file>
If you want to do this permanently, you need to create your own FileStorage class
import os from django.conf import settings from django.core.files.storage import FileSystemStorage class 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 MyFileStorage mfs = MyFileStorage() class SomeModel(model.Model): my_file = model.FileField(storage=mfs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With