How do I reference a Django settings variable in my models.py?

DjangoDjango ModelsDjango Settings

Django Problem Overview


This is a very beginner question. But I'm stumped. How do I reference a Django settings variable in my model.py?

NameError: name 'PRIVATE_DIR' is not defined

Also tried a lot of other stuff including settings.PRIVATE_DIR

settings.py:

PRIVATE_DIR = '/home/me/django_projects/myproject/storage_dir'

models.py:

# Problem is here.
from django.core.files.storage import FileSystemStorage

fs = FileSystemStorage(location=PRIVATE_DIR)

class Customer(models.Model): 
    lastName = models.CharField(max_length=20) 
    firstName = models.CharField(max_length=20) 
    image = models.ImageField(storage=fs, upload_to='photos', blank=True, null=True)

What's the correct way to do this?

Django Solutions


Solution 1 - Django

Try with this: from django.conf import settings then settings.VARIABLE to access that variable.

VARIABLE should be in capital letter. It will not work otherwise.

Solution 2 - Django

from django.conf import settings

PRIVATE_DIR = getattr(settings, "PRIVATE_DIR", None)

Where it says None, you will put a default value incase the variable isn't defined in settings.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncodingJoeView Question on Stackoverflow
Solution 1 - DjangojuankysmithView Answer on Stackoverflow
Solution 2 - DjangoHelpyHelpertonView Answer on Stackoverflow