191

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?

daaawx
  • 3,273
  • 2
  • 17
  • 16
codingJoe
  • 4,713
  • 9
  • 47
  • 61
  • 10
    `from django.conf import settings` - https://docs.djangoproject.com/en/dev/topics/settings/#using-settings-in-python-code – wkl Oct 23 '11 at 17:27

3 Answers3

427

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.

Greg
  • 5,862
  • 1
  • 25
  • 52
juankysmith
  • 11,839
  • 5
  • 37
  • 62
  • 28
    Something relevant: if you have several instances of `settings_something.py` due to a project deployed in several environments, do not try to import from `app.settings`. Overwritten variables in the other files won't take effect. Always use the import mentioned in this answer. It took me a few hours to realize what was going on in my project. – Ev. Jun 08 '16 at 13:42
  • 1
    This works, if it is properly configured: with environment variable DJANGO_SETTINGS_MODULE or with manage.py command line parameter --settings=.. Read more in docs: https://docs.djangoproject.com/en/2.0/topics/settings/ – mirek Feb 08 '18 at 20:51
128
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.

poiuytrez
  • 21,330
  • 35
  • 113
  • 172
HelpyHelperton
  • 1,715
  • 3
  • 14
  • 10
3

There's an example of importing the EMAIL_HOST_USER from the settings.py file and use it to send an email:

from django.conf import settings
from django.core.mail import send_mail

def post_share(request, post_id): 
   # ...
   send_mail(subject, message, settings.EMAIL_HOST_USER, [
                      settings.EMAIL_HOST_USER, 'ahmnouira@gmail.com'])
ahmnouira
  • 1,607
  • 13
  • 8