user13662320
user13662320

Reputation:

How can I store files in Django

How can I be able to store files in Django in a model?

Well, I know about the FileField but I don't understand how it works the thing is that I want to be able to store the file and no the path cause like I am making a cloud storage website for a project and want to be able to store the file.

And how could I be able to change the file name when a user wants to change it.

Upvotes: 0

Views: 1677

Answers (1)

dVeza
dVeza

Reputation: 552

I'll try to explain simply how it works as it'll help you decide the best solution for you.

  1. Local system storage.

You store the path in the database, and set the storage class on the field as, FileSystemStorage which means django will know to write and read from the hard disk of the same system your django app is running on. So basically you store normal files with references to their location in a directory.

  1. Cloud storage.

Similar to local system, but instead of a local path you save a uri location, and instead of the local system you'll fetch the file over the network either via http, or a custom protocol like s3. In order to achieve this you need to declare a custom storage class, where you define your custom save and delete methods to upload and delete from your cloud storage.

You can write your own: https://docs.djangoproject.com/en/3.1/howto/custom-file-storage/

Or use a library: https://github.com/jschneier/django-storages

  1. Database storage

If you know files are text, you can read them and save the text directly in the database with associated metadata. If they are binary you can store them as Blob type - the risk here is slow performance and risk of bloating the database. AFAIK it's a better practice to store binaries outside the database.

Upvotes: 2

Related Questions