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

不想你离开。 提交于 2020-01-20 12:28:41

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/7867797/how-do-i-reference-a-django-settings-variable-in-my-models-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!