Uploading a file in any application is pretty much a trivial process. I found a really nice blog over here

How to Upload Files With Django
Updated at Aug 1, 2016: As suggested by@fapolloner, I’ve removed the manual file handling. Updated the example using…simpleisbetterthancomplex.com

But we had a more complex requirement, where there were various entities which required files to be associated with them as an attachments and that too of different types like video, audio or text. One obvious way is to create a separate relation for each of the file type. But we were looking for something more sophisticated.

Django ContentTypes

Django supports a special framework called contenttypes which allows us to include generic foreign keys in our model.

A normal ForeignKey can only “point to” one other model, which means that if the TaggedItem model used a ForeignKey it would have to choose one and only one model to store tags for. The contenttypes application provides a special field type (GenericForeignKey) which works around this and allows the relationship to be with any model:

Below is the example code for Models with contenttype

There are three parts to setting up a GenericForeignKey:

  1. Give your model a ForeignKey to ContentType. The usual name for this field is content_type.
  2. Give your model a field that can store primary key values from the models you’ll be relating to. For most models, this means a PositiveIntegerField. The usual name for this field is object_id.
  3. Give your model a GenericForeignKey, and pass it the names of the two fields described above. If these fields are named content_type and object_id, you can omit this – those are the default field names GenericForeignKey will look for.

For those new to Python attachment_upload in line number 10 is a callable which returns a path of the file location and internally called by model.FileField

Below is the implementation of attachment_upload

instance and filename are internally passed by FileField object.

Saving the file

Retrieving the file

We created a separate method for this purpose, all we need to do now is to pass the object of the model with which the file is associated as a parameter to this method and this method will return us the list of URLs of all the files.

Click here for more details…

At BoTree Technologies, we build enterprise applications with our Django team of 20+ engineers.

We also specialize in RPA, AI, Python, Ruby on Rails, JavaScript and ReactJS.

Consulting is free – let us help you grow!