Ever since I changed my settings.py file to be in 3 different files (i.e. base, local and production) within a subfolder 'settings', BASE_DIR will not display the path to project correctly.
What I want BASE_DIR to output is the following:
`PathToProject/Projectname`
what I am getting (since I moved BASE_DIR in base.py within 'settings' subfolder:
PathToProject/Projectname/Projectname
It bothers me because now it's looking for static folder within Projectname/Projectname instead of Projectname
How could I properly configure BASE_DIR function to give me the correct path to project?
About having several custom settings.py files :
I suggest you to keep your default main settings.py and make custom ones aside if you need some.
If you need to derivate it, make other settings.py files for instance for your preproduction version. make your preprod-settings.py like this, in the same directory that settings.py :
from .settings import *
DEBUG = False # <-- just add some settings or override the previous ones like this.
This way all your main settings are in the main file, and you only need to put what you want to change in your custom settings files. You'll then be able to change what settings file to use with the manage.py's --settings option, or by modifying (or make a custom one) wsgi.py file in production, with for instance :
import os, sys
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.mycustomsettingsfile")
SETTINGS_DIR = os.path.dirname(__file__)
PROJECT_PATH = os.path.abspath(os.path.join(SETTINGS_DIR, os.pardir))
sys.path.append(PROJECT_PATH)
application = get_wsgi_application()
How BASE_DIR (should) works :
When creating your project, BASE_DIR's default value is :
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
which means :
"BASE_DIR is the parent folder of the parent folder of the file this line is in (settings.py).".
os.path.dirname() gives the parent folder path, and os.path.abspath() the absolute path (you need it to give os.path.dirname() enough informations to get the parent dirnames).
Since BASE_DIR's value is computed each time you run your server, and since this valus simply depends of the settings.py location, you don't need custom values for several locations or cases :
You move your project --> BASE_DIR automatically changes.
"But what if I move my settings.py?"
If you move your settings.py file, you may have to change the BASE_DIR value : for instance, if you move it deeper, just add a os.path.dirname to your BASE_DIR assignation.
NB : if you want to choose what project to run amongst several subprojects (it seems weird to me though, I'm not sure I understood well. It could ever be wrong, feel free to describe what you want to achieve and why, maybe we could suggest a better way), you could still override the BASE_DIR value in your custom settings.py files.
Related
I'm forced to keep my .env file in a non-standard path outside the root of my project (in a separate directory altogether).
Let's say I have my Django project in /var/projects/my_project, though I have my .env file in /opt/envs/my-project/.env where my SECRET_KEY is stored. In my settings.py file, I'd like to explicitly use the .env file at that path so that I can still do this:
from decouple import config
secret_key = config('SECRET_KEY')
I figured it out.
Instead of importing decouple.config and doing the usual config('FOOBAR'), create a new decouple.Config object using RepositoryEnv('/path/to/env-file').
from decouple import Config, RepositoryEnv
DOTENV_FILE = '/opt/envs/my-project/.env'
env_config = Config(RepositoryEnv(DOTENV_FILE))
# use the Config().get() method as you normally would since
# decouple.config uses that internally.
# i.e. config('SECRET_KEY') = env_config.get('SECRET_KEY')
SECRET_KEY = env_config.get('SECRET_KEY')
Hopefully this helps someone.
If you look at the decouple implementation, config is just a pre-instantiated AutoConfig:
config = AutoConfig()
But AutoConfig takes as optional argument search_path so we can do the following:
from decouple import AutoConfig
config = AutoConfig(search_path='/opt/envs/my-project')
Then you can do as usual:
secret_key = config('SECRET_KEY')
Now, django-decouple==2.1 supports having settings.ini and .env files in any parent directory of the project dir.
(And the old methods don't work anymore. - from decouple import Config, RepositoryEnv does not work, AutoConfig does not have search_path as parameter.)
This is convenient because you would want to keep the settings.ini in the project folder on your local machine and you would want to have clean checkouts on the staging/prod server, thus the settings.ini is better located outside the project folder.
I have the following directory structure for a program I'm writing in python:
\code\
main.py
config.py
\module_folder1\
script1.1.py
\data\
data_file1
data_file2
My config.py is a set of global variables that are set by the user, or generally fixed all the time. In particular config.py defines path variables to the 2 data files, something like path1 = os.path.abspath("../data/data_file1"). The primary use is to run main.py which imports config (and the other modules I wrote) and all is good.
But sometimes I need to run script1.1.py by itself. Ok, no problem. I can add to script1.1 the usual if __name__ == '__main__': and I can import config. But then I get path1 = "../code/data/data_file1" which doesn't exist. I thought that since the path is created in config.py the path would be relative to where config.py lives, but it's not.
So the question is, how can I have a central config file which defines relative paths, so I can import the config file to scripts in different directories and have the paths still be correct?
I should mention that the code repo will be shared among multiple machines, so hardcoding an absolute path is not an option.
You know the correct relative path to the file from the directory where config.py is located
You know the correct relative path to the directory where config.py is located (in your case, ..)
Both of this things are system-independent and do not change unless you change the structure of you project. Just add them together using os.path.join('..', config.path_repative_to_config)
(Not sure who posted this as a comment, then deleted it, but it seems to work so I'm posting as an answer.) The trick is to use os.path.dirname(__file__) in the config file, which gives the directory of the config file (/code/) regardless of where the script that imports config is.
Specifically to answer the question, in the config file define
path1 = os.path.abspath(os.path.join(os.path.join(os.path.join( os.path.dirname(__file__) , '..'), 'data' ), 'data_file1' ) )
I am a beginner working on Django Project.
Settings.py file of a Django project contains these two lines:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
I want to know the difference as I think both are pointing to the same directory. Also it would be great help if you could provide some links os.path functions.
BASE_DIR is pointing to the parent directory of PROJECT_ROOT. You can re-write the two definitions as:
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(PROJECT_ROOT)
because the os.path.dirname() function simply removes the last segment of a path.
In the above, the __file__ name points to the filename of the current module, see the Python datamodel:
__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file.
However, it can be a relative path, so the os.path.abspath() function is used to turn that into an absolute path before removing just the filename and storing the full path to the directory the module lives in in PROJECT_ROOT.
Let's say I have the following settings.py:
LOCALE_PATHS = (
'/conf/locale'
)
DEBUG = True
Can I read value of DEBUG from my python code?
Can I get full path to my language file (django.mo) django uses taken into consideration my LOCALE_PATHS value?
Yes, you can import settings and look for your values:
from django.conf import settings
print settings.DEBUG
Included in a separate comment was the following from LA_:
"Thanks, Joseph. If I print settings.LOCALE_PATHS, it prints exactly the value I defined. How could I get the full path django uses?"
What may be useful for you to do is record the absolute path by using the os.path module.
For example, you could do the following:
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
LOCALE_ABS_PATH = os.path.join(PROJECT_PATH, LOCALE_PATHS[0])
Then you could reference LOCALE_ABS_PATH as the absolute path to the LOCALE_DIRS listed in settings.py
Let me know if this is helpful at all. I'm not entirely sure of the context with which you plan to implement that, but perhaps I could help more if you continue to have trouble.
I am new in Python and i am studying this code. I am trying to figure out what is the meaning of the terms like PROJECT_ROOT i suspect it is something like an event. I have imported the os in the GUI but when i searched the term by typing help(os) i did not find it in there
#Django settings for pysec project
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
I 've searched many tutorials from python site and the documentation but i did not find the meaning of these commands.
I've searched other words in os also like ADMINS and DEBUG
This kind of code can look intimidating, but the only purpose of code like this is to define some project-wide constants that you can use where ever you want. You could set your own constants if you like and nothing would break, they just would be used, like so:
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
MY_VARIABLE = "nonsense"
The only point is so that elsewhere (assuming the above file is named settings.py) you can write something like this:
from settings import PROJECT_ROOT
or
import settings
print settings.PROJECT_ROOT
Specifically, PROJECT_ROOT is a path to the current file, DEBUG is really just a boolean set to True, TEMPLATE_DEBUG is then also set to that same boolean (True), and so on and so forth.
The definition of these constants is simple, the complicated parts are what Django actually does with these constants when it comes time to use them. If you want to understand that, you have to dig into some django source code.
All your questions are answered in the docs, available here on the Django site. You should read the Django tutorial before proceeding or you'll get stuck on every single feature of Django!
os is a module in the Python standard library, see documentation. os.path is a submodule, see documentation.
__file__ is a path to the current file (the Python file this code is in, probably "./settings.py" or so).
os.path.dirname takes a path and returns the directory part of it (the path minus settings.py).
os.path.abspath turns a path into an absolute path.
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) makes the setting "PROJECT_ROOT" equal to the absolute path of the directory that settings.py is in.
settings.py contains perfectly normal Python code that is executed when Django starts up, Django imports variables from it and that's how you configure Django.
PROJECT_ROOT is Django magic, normally you don't need to worry about it. You can see that Django skeleton code dynamically infers it from the path of current Python source file.
I think it's used to find own resources (e.g. static images) once this code is deployed.
Please see https://stackoverflow.com/a/16413955/705086