Trouble setting up sqlite3 with django! :/ - python

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')

Related

How do you use python-decouple to load a .env file outside the expected paths?

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.

Importing path to settings Django (django-rest-auth)

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'

How to make python config file, in which relative paths are defined, but when scripts in other directories import config, paths are correct?

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' ) )

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.

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

Categories

Resources