How to store image in Django - use link or no?

Viewed 45

I have field:

image = models.ImageField(
        max_length=500,
        upload_to='images'
    )

and some settings to upload an image to AWS S3 Bucket, where PublicMediaStorage is my custom storage:

PUBLIC_MEDIA_LOCATION = 'media'
AWS_S3_MEDIA_ENDPOINT_URL = env('AWS_S3_MEDIA_ENDPOINT_URL', None)
DEFAULT_FILE_STORAGE = 'new_project.storages.PublicMediaStorage'

I need to store and get my images from database(postgres). For now my image stores at the database like here. And if i write image.url i will get the url of my image(that's why I don't need to store urls of images in my database). But is it right way? Maybe it will be better to store immediately links at the database? Any solutions?

1 Answers

OP is doing well using ImageField . OP might want to add blank=True so that OP's forms don't require the image.

image = models.ImageField(upload_to='images', blank=True)

The reason to use ImageField is that it checks whether the image is valid and also uploads it to the right location, which is something one wouldn't get with a simple URL. That is why the docs mention it requires the Pillow library.

With regards to the DB path, it is better to store the the relative path. OP can access the rest of the URL in the template if needed too and if the rest of the URL changes then OP only has to change in one place and not in the database(s).

Related