Save photos outside django folder in production

Hi, here’s my code but it doesn’t work:

def path_and_rename(instance, filename):
ext = filename.split(‘.’)[-1]
# get filename
if instance.pk:
filename = ‘{}.{}’.format(instance.pk, ext)
else:
# set filename as random string
filename = ‘{}.{}’.format(uuid4().hex, ext)
# return the whole path to the file
return os.path.join(‘account/’, filename)

class Profile(models.Model):
picture = models.FileField(upload_to=path_and_rename)

# settings.py

DEBUG = False
MEDIA_ROOT = “/Users/myuser/Desktop/django-sample/”
MEDIA_URL = “account/”

Once I try to upload a photo using django admin terminal the source is not uploaded anywhere.
I know this is not a good approach in production mode, but it’s the start of my project and I don’t want to spend money for Amazon S3 o similar services for now.

Does someone have a solution?
Thank you

First, this code is not properly indented and will not run as posted here. Also, where does this function reside?

How are you running this? Is this being done in your local development environment? Are you running this using runserver? (If not, how?)

There should be some error messages generated by your server.

You could add a print statement in that function to show you what you’re getting as the instance and filename parameters, along with the value of the filename that you’re generating.

I’m running this code on my local machine using docker-compose and I don’t get any error from the server.

Here’s how I handle error logs:

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "verbose": {
            "format": "%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s"
        },
        "simple": {"format": "%(levelname)s %(message)s"},
    },
    "handlers": {
        "file": {
            "level": "WARNING",
            "class": "logging.FileHandler",
            "filename": "errors.log",
            "formatter": "verbose",
        },
    },
    "loggers": {
        "errors": {
            "handlers": ["file"],
            "propagate": True,
            "level": "WARNING",
        },
    },
}

And after saving the file, there are no erorrs.

Is that MEDIA_ROOT directory inside the container or is it a volume mount to a physical directory outside the container? If outside, what’s the mount command look like for it?

I tried to map the folder as you said, and now it works, thank you.
Here’s my docker-compose configuration.

  app:
    build: .
    command: python /code/manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
      - ../photos/:/code/media
    ports:
      - 8000:8000
    depends_on:
      - database