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
Related
I am stuck with very trivial thing in Django, and that is I don't know how to define path to REGISTER_SERIALIZER in main settings file. I am using http://django-rest-auth.readthedocs.io/en/latest/configuration.html. I added all the apps, and it works without custom serializer. I just need to know how to add valid path this (you can check link for library example).
This is what I tried:
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER' : os.path.join(BASE_DIR, "rest\\rest_user_profile\\serializers.RegisterSerializer")
}
the path is correct and still I get
ImportError: No module named 'C:\\...\\rest\\rest_user_profile\\serializers'
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.
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.
The Django docs say that I can call settings.configure instead of having a DJANGO_SETTINGS_MODULE. I would like my website's project to do this. In what file should I put the call to settings.configure so that my settings will get configured at the right time?
Edit in response to Daniel Roseman's comment:
The reason I want to do this is that settings.configure lets you pass in the settings variables as a kwargs dict, e.g. {'INSTALLED_APPS': ..., 'TEMPLATE_DIRS': ..., ...}. This would allow my app's users to specify their settings in a dict, then pass that dict to a function in my app that augments it with certain settings necessary to make my app work, e.g. adding entries to INSTALLED_APPS.
What I envision looks like this. Let's call my app "rexe_app". In wsgi.py, my app's users would do:
import rexe_app
my_settings = {'INSTALLED_APPS': ('a','b'), ...}
updated_settings = rexe_app.augment_settings(my_settings)
# now updated_settings is {'INSTALLED_APPS': ('a','b','c'), 'SESSION_SAVE_EVERY_REQUEST': True, ...}
settings.configure(**updated_settings)
Its not quite equivalent, since settings DJANGO_SETTINGS_MODULE updates defaults, found in django.conf.settings.global_settings, while parameter for configure completely ignores them, so you have to add some additional processing.
Beware, first, that you can't modify INSTALLED_APPS on the fly, as they are examined once on settings processing. For example, to apply modifications to INSTALLED_APPS in Apache-deployed application, you need to restart Apache.
Second, as settings are imported, therefore this point is prone to injections of some sorts, and is highly vulnerable to expose them to users.
If this is a meta app, there are two possibilities:
If you want to provide default settings for `django`-wise setting, add following to `default_settings.py` in your app:
INSTALLED_APPS = ('default_app', )
Just make sure you don't import `default_settings.py` in your app, and make your users add to their settings.py
from rexe_app.default_settings import *
INSTALLED_APPS += ('users_app', )
that effectively will set `INSTALLED_APPS` to `('default_app', 'users_app', )` for your end users.
In case you need `rexe_app`-wise settings, you can default them in your app's `__init__.py`:
from django.conf import settings
REXE_APP_CONFIG_PARAM = getattr(settings, 'REXE_APP_CONFIG_PARAM',
'default_param_value')
so when user needs to change default `REXE_APP_CONFIG_PARAM` he needs to just add
INSTALLED_APPS = ('rexe_app')
REXE_APP_CONFIG_PARAM = 'user_param_value'
to his `settings.py`.
It would be in your wsgi script. please have look at the docs.
You could run mysite.settings.configure() instead of os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
If you are using wsgi then call that in your wsgi script before running the app.
If you want to do this for dev server, pass it as command line option (mentioned on the same page).
django-admin.py runserver --settings=mysite.settings
I'm in the settings.py module, and I'm supposed to add the directory to the sqlite database. How do I know where the database is and what the full directory is?
I'm using Windows 7.
The absolute path of the database directory is what you need. For e.g. if your database is named my.db and lives in C:\users\you\ then:
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'C:/users/you/my.db'
Update
AFAIK you do not have to create the database yourself. The database will be created when you run syncdb. The database can live in any directory you wish. If you want the database to be in you Django project directory just change the path accordingly.
For e.g. let us say your Django project lives in C:\users\you\myproject\. You would then change your settings thus:
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'C:/users/you/myproject/my.db'
if you don't provide full path, it will use the current directory of settings.py,
and if you wish to specify static path you can specify it like: c:/projects/project1/my_proj.db
or in case you want to make it dynamic then you can use os.path module
so os.path.dirname(file) will give you the path of settings.py and accordingly you can alter the path for your database like os.path.join(os.path.dirname(file),'my_proj.db')