How to verify if django settings are applied correctly? - python

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.

Related

BASE_DIR output within a subfolder, DJANGO

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.

How to get the location of a Zope installation from inside an instance?

We are working on an add-on that writes to a log file and we need to figure out where the default var/log directory is located (the value of the ${buildout:directory} variable).
Is there an easy way to accomplish this?
In the past I had a similar use case.
I solved it by declaring the path inside the zope.conf:
zope-conf-additional +=
<product-config pd.prenotazioni>
logfile ${buildout:directory}/var/log/prenotazioni.log
</product-config>
See the README of this product:
https://github.com/PloneGov-IT/pd.prenotazioni/
This zope configuration can then be interpreted with this code:
from App.config import getConfiguration
product_config = getattr(getConfiguration(), 'product_config', {})
config = product_config.get('pd.prenotazioni', {})
logfile = config.get('logfile')
See the full example
here: https://github.com/PloneGov-IT/pd.prenotazioni/blob/9a32dc6d2863b5bfb5843d441e652101406d9a2c/pd/prenotazioni/init.py#L17
Worth noting is the fact that the initial return avoids multiple logging if the init function is mistakenly called more than once.
Anyway, if you do not want to play with buildout and custom zope configuration, you may want to get the default event log location.
It is specified in the zope.conf. You should have something like this:
<eventlog>
level INFO
<logfile>
path /path/to/plone/var/log/instance.log
level INFO
</logfile>
</eventlog>
I was able to obtain the path with this code:
from App.config import getConfiguration
import os
eventlog = getConfiguration().eventlog
logpath = eventlog.handler_factories[0].instance.baseFilename
logfolder = os.path.split(logpath)[0]
Probably looking at in the App module code you will find a more straightforward way of getting this value.
Another possible (IMHO weaker) solution would be store (through buildout or your prefered method) the logfile path into an environment variable.
You could let buildout set it in parts/instance/etc/zope.conf in an environment variable:
[instance]
recipe = plone.recipe.zope2instance
environment-vars =
BUILDOUT_DIRECTORY ${buildout:directory}
Check it in Python code with:
import os
buildout_directory = os.environ.get('BUILDOUT_DIRECTORY', '')
By default you already have the INSTANCE_HOME environment variable, which might be enough.

Unknown statement type in Django

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

Django: where do I call settings.configure?

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

Django can't find template - Polls App Part 3

I am following the polls app tutorial part 3 and I cannot get the templates to be found
This is the exact error
polls/index.html
Request Method: GET
Request URL: http://localhost:8000/polls/
Django Version: 1.4.3
Exception Type: TemplateDoesNotExist
Exception Value:
polls/index.html
Exception Location: c:\Python27\lib\site-packages\django\template\loader.py in find_template, line 138
Python Executable: c:\Python27\python.exe
Python Version: 2.7.2
So in my settings.py I have put the directory there. "C:/Scripts/mysite/template" and created /polls/index.html
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
"C:/Scripts/template"
"C:/Scripts/mysite/template"
)
It for some reason cannot find it though. Any ideas?
This is the exact instruction from the tutorial.
create a directory, somewhere on your filesystem, whose contents Django can access. (Django runs as whatever user your server runs.)
You're missing a comma at the end of the first line:
"C:/Scripts/template", # <--- HERE
"C:/Scripts/mysite/template"
without that, Python automatically concatenates the two strings (because they're inside parens) so that it just becomes "C:/Scripts/templateC:/Scripts/mysite/template".
Debug
from your applications main folder, run the following command: python manage.py shell this is going to bootstrap your app with the settings file.
type from django.conf import settings and hit enter
type settings.TEMPLATE_DIRS and check the output. Do you see the template directories that you specified?
Absolute paths relative to the settings.py file
I generally use absolute paths relative to the settings.py file. That way collaborators can share a main settings file, and no matter what system/environment you deploy to your paths will be correct.
to do this:
# settings.py
import os
# ... other settings
TEMPLATE_DIRS = (
os.path.join(os.path.normpath(os.path.dirname(__file__)), 'templates'),
)
let me know if the debug step didn't help, and i'll try and supply some more help.

Categories

Resources