Timothy Oliver
Timothy Oliver

Reputation: 550

Storing File in Json Field, Django

I'm working on a project which requires users to submit posts of various forms.

There are posts that require images and others that require videos. To deal with this and other complexities, I was thinking of using jsonfields.

My current issue is handing files, that is images and videos. I was hoping to be able to store the file url in a field in the json field but I haven't come across anything like that on the internet.

Is it possible or advisable to go on with this approach? If so, how can it be done?

Upvotes: 0

Views: 982

Answers (2)

ihoryam
ihoryam

Reputation: 2481

You can use S3 like services for that either AWS S3 or any alternative. If you need a local one and don't want to go with 3-party services you can take a look on minio which can be setup locally on any server. The idea is following You setup minio/s3 service and use it as media storage for you django app (check out django-storages )

So whenever you'll create a post you can upload all the media or static files to the s3 and use an url in your post object instead.

Upvotes: 1

Aram Darakchian
Aram Darakchian

Reputation: 133

You can use Django's FileField https://docs.djangoproject.com/en/3.1/ref/models/fields/#filefield Works well with django-rest-framework. It works exactly as you expect (i.e. returns URL to the saved file).

I prefer to use S3 as a storage via S3Boto3Storage from django-storages. You can define a custom storage like

class MyCustomStorage(S3Boto3Storage):
    location = 'private'
    default_acl = 'private'
    file_overwrite = False
    custom_domain = False

and then in your model:

class MyModel(models.Model):
    ...more fields...
    attachment = models.FileField(storage=MyCustomStorage(), null=True)
    ...more fields...

Upvotes: 1

Related Questions