Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Django's FileField to an existing file

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?

like image 386
Guard Avatar asked Nov 30 '11 20:11

Guard


People also ask

How do I save a FileField in Django?

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.

What is default storage in 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.

How do I store images in Django?

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.


2 Answers

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> 
like image 198
bara Avatar answered Sep 19 '22 22:09

bara


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) 
like image 35
Burhan Khalid Avatar answered Sep 22 '22 22:09

Burhan Khalid