Home > Enterprise >  ImageField storage options based on settings
ImageField storage options based on settings

Time:11-16

I am using django-storages with the Azure backend. I would like to use the local provided Django solution when running locally and the Azure storage when running in production. How would I change this based on the settings? Do I just use an IF statement below these?

# local
image = models.ImageField(upload_to="profile_pics", blank=True, null=True)
# production
image = models.ImageField(upload_to="profile_pics", blank=True, null=True, storage=AzureMediaStorage())

CodePudding user response:

You can set the default storage in your settings.py here, and change it for production or debug environments. This will change the storage throughout the entire application.

If you want to set the storage for only some fields, you can use a callable:

from django.conf import settings
from django.db import models
from .storages import MyLocalStorage, MyRemoteStorage
from django.core.files.storage import default_storage


def select_storage():
    return default_storage if settings.DEBUG else AzureMediaStorage()


class MyModel(models.Model):
    image = models.ImageField(upload_to="profile_pics", blank=True, null=True, storage=select_storage)
  • Related