Python Django set DJANGO_SETTINGS_MODULE when migrating source code - django

Task: Set up a new running environment by being provided python/Django source code and some additional details.
Problem: Cannot get Django-admin to validate due to missing/incorrect settings configuration
"django.core.exceptions.ImproperlyConfigured Requested setting USE_I18N, but settings are not configured. ..... "
You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
Env Details: Ubuntu OS, Python 2.7, Django 1.7, PostgreSQL (also Supervisor + gunicorn) Running a venv located **/home/dave/python-env/vas/**bin/activate
Python sys.path
/usr/lib/python2.7/* (multiple defined)
/home/dave/python-env/vas/python2.7/site-packages
So tried several methods (including #export DJANGO_SETTINGS_MODULE=project-name.settings....) with little success.
How can one set the DJANGO_SETTINGS_MODULE variable?
os.environ.setdefault() is set in wsgi (I know this is the next step)
BUT this value is also set in /manage.py ...?
os.environ.setdefault("DJANGO_SETTINGS_MODULE", project_name.settings)
The directory /var/www/app/ (where the python source code is located) has several files, one of them is the project_name where the settings.py sits....
I am new to python/django...
Trying to get django-admin.py validate to validate.
Update: Running #python manage.py runserver runs OK. #python manage.py validate|check returns "System check identified no issues (0 silenced)
Running #django-admin.py check returns the error in question. "You must either define DJANGO_SETTINGS_MODULE ...."
UPDATE 2: Solution
Turns out you don't need django-admin.py as suggested by (Alasdair) and you can use manage.py.
Details - If the 'manage.py check' function returns no issues and #pip install -r requirements.txt completes within your virtual environment THEN one can run #manage.py createsuperuser
I was able to use #manage.py runserver after creating a super user, and using this new user (as the database tables were empty for security reasons) I was able to log into 127.0.0.1:8000/admin. From there the models/tables were visible and using the admin functions I could create a new user + group to access the original system that was being migrated as an admin user.
Also not that a database was required (running postgres) with db/username/pass as per settings files and a git repository (at least empty initialised) for raven...
hope this helps someone coming into python.

Related

Created a brand new Django Project, attempting to run the server generates an Improperly Configured Error

I have been working on a Django Project for a bit, until I took a break. One month later I dug back in to the project and went to run the server. I received an error:
django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
I figured I must have tweaked something by accident. So I created a brand new Django Project (using a virtual environment), and just went to test the server. I received the same error. I tried the python manage.py shell solution listed in another answers but to no avail.
If it helps I'm on Linux with Django version 2.1.5 and Python 3.6.
Edit:
If anyone encounters something similar I found using python3 manage.py runserver works in place of using django-admin. Per Greg's answer below, I did begin to receive a new error ModuleNotFoundError: No Module named "mysite" exists. I will continue to search for an answer on that front.
Going off of the comments here.
If "env | grep DJANGO_SETTINGS_MODULE" returns empty, it means you have to set an environment variable stating where your settings.py file is located.
This can be done by doing the following:
export DJANGO_SETTINGS_MODULE=mysite.settings
Be sure to replace "mysite" with the name of your app!

Where do I set environment variables for Django?

everyone!
Django 1.11 + PostgreSQL 9.6 + Gunicorn + Ubuntu 16.04 in AWS
I want to set environment variables for sensitive info.(django secret key, DB password...)
I studied many articles about setting ways.
But when I tried os.environ['env_name'],
.bashrc: Not working
.bash_profile: Not working
.profile: Not working
/etc/environment: Not working
Gunicorn script file.(systemd): I set them in gunicorn systemd script. It work very well.
But because I want to use the environment variables in other program too, I set them among 1~5 configurations. I don't understand why 1~5 configurations didn't work. Is there scope or priority of setting environment variables?
EDIT:
I use Ubuntu 16.04 server. I can't restart terminal session.
I tried 'source .bashrc' and logout/login. But It didn't work.
Of cource, 'echo $some_env_var' is working, I say, django can't read.
.bashrc will work for local development but not for a production environment. I just spent quite a bit of time looking for the answer to this and here's what worked for me:
1) Create a file somewhere on your server titled settings.ini. I did this in /etc/project/settings.ini
2) Add your config data to that file using the following format where the key could be an environmental variable and the value is a string. Note that you don't need to surround the value in quotes.
[section]
secret_key_a=somestringa
secret_key_b=somestringb
3) Access these variables using python's configparser library. The code below could be in your django project's settings file.
from configparser import RawConfigParser
config = RawConfigParser()
config.read('/etc/project/settings.ini')
DJANGO_SECRET = config.get('section', 'secret_key_a')
Source: https://code.djangoproject.com/wiki/SplitSettings (ini-style section)
The simplest solution is as already mentioned using os.environ.get and then set your server environment variables in some way (config stores, bash files, etc.)
Another slightly more sophisticated way is to use python-decouple and .env files. Here's a quick how-to:
1) Install python-decouple (preferably in a venv if not using Docker):
pip install python-decouple
2) Create a .env file in the root of your Django-project, add a key like;
SECRET_KEY=SomeSecretKeyHere
3) In your settings.py, or any other file where you want to use the configuration values:
from decouple import config
...
SECRET_KEY = config('SECRET_KEY')
4) As you probably don't want these secrets to end up in your version control system, add the file to your .gitignore. To make it easier to setup a new project, you could have a .env_default checked into the VCS containing default/dummy-values that's not used in production.
create a file called .bashrc in your server
export('the_name_in_bashrc', some_value)
then in the settings.py
import os
some_variable = os.environ.get('the_name_in_bashrc')
If you're using a virtual ENV you can add the environment variables to that specific environment. You can use export KEY=VALUE in your terminal but that will not persist. If you would like your values to persist you can edit the file:
sudo nano your_environment/bin/activate
Then at the bottom add the values you want e.g.:
export MY_KEY="12345"
And save. Remember to restart your ENV for changes to take effect.
pip install python-dotenv
Go To settings.py
import os
from dotenv import load_dotenv
load_dotenv('.env')
SECRET_KEY = os.getenv('SECRET_KEY')
Go To .env file
SECRET_KEY = your_secret_key

django - How to manually set sys.path?

Till now I was making change on my django production server (yes, really really bad :p ). I am wanna to go to a git process, and creating a local test server before deployement. So, I downloaded my python files, and ran a :
python manage.py runserver
hoping and prayed... but it was not enough, I got a nice error :
django.core.exceptions.ImproperlyConfigured: WSGI application 'issc.issc.wsgi.application' could not be loaded; Error importing module: 'No module named issc.wsgi'
I read in the documentation that [manage.py] is created automatically and sets up several key parts :
In addition, manage.py is automatically created in each Django project. manage.py is a thin wrapper around django-admin.py that takes care of several things for you before delegating to django-admin.py:
It puts your project’s package on sys.path.
It sets the DJANGO_SETTINGS_MODULE environment variable so that it points to your project’s settings.py file.
It calls django.setup() to initialize various internals of Django.
My question is : how can I manually set up these variables ? Because in my case I downloaded all the files on an arbitrary directory, but it was not enough. Eveything is here, but it is missing the link to this everything....
If you want to manually set the address of your config file, you can set DJANGO_SETTINGS_MODULE with the following:
export DJANGO_SETTINGS_MODULE='settings_to_load'
You can set all your environmental variables this way and it should work. I recommend to use a Virtualenv to this at least.

My Django secret key is in an environment variable but I can't do syncdb

I'm setting up a Django project with different files for local and production settings. I can confirm that my Django secret key is successfully in an environment variable in virtualenv and when I do runserver I get no error. However when I try manage.py syncdb I get
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
I don't understand why I can successfully browse to the site after runserver but I can't sync the database. When I run env I can see that the secret key is there and in my base settings file (imported into local settings) I am doing this:
SECRET_KEY = os.environ.get('MY_SECRET_KEY')
Any help debugging this would be greatly appreciated.
Euan
I'm not sure why the runserver command is working while syncdb isn't, but you can sort it out by adding a environment variable for DJANGO_SETTINGS_MODULE in the same way you did for the SECRET_KEY. The only difference is that you don't need to reference DJANGO_SETTINGS_MODULE within the django code anywhere. I'm running my own setup in exactly that way and the only problem I run into is forgetting to change the settings module when I switch between projects :-)
EDIT: I didn't realise that you were adding --settings=myapp.settings.local to runserver as well as syncdb. The reason you need to do this is that you are using settings on a different path from the default so python can't find them. Also, although you set the DJANGO_SETTINGS_MODULE in the wsgi file, this is only fired when the site is accessed via your webserver. When running a manage command the wsgi file is ignored (AFAIK) so adding DJANGO_SETTINGS_MODULE to your environment variables in the same way as SECRET_KEY makes your settings file available to the manage command.
Hope that helps
Somewhat similar situation here, using virtualenv running an outer script which involves django models.
To make this work please make sure:
Your sys.path list has a path to your virtualenv site-packages. For me it's: sys.path.append('/home/user/.virtualenvs/Project/local/lib/python2.7/site-packages')
Your django settings variable is added to os.environ. Eg: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Project.settings")

Can't sign in to Django admin

I can't sign in to Django admin with any of the superusers I've created. Tried creating new superusers, changing passwords, etc. - no error messages for any of these processes, but still can't sign in.
I'm not sure if it's related, but I also can't run django-admin.py commands. Here is what I've done so far:
$ django-admin.py validate
Error: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
$ export DJANGO_SETTINGS_MODULE=mysite.settings
$ django-admin.py validate
Error: Could not import settings 'mysite.settings' (Is it on sys.path? Does it have syntax errors?): No module named mysite.settings
sys.path shows ['/Users/joerobinson/Sites/django/mysite' ... (other stuff on path)]
Is there something else I need to do to register the mysite module?
python manage.py runserver works fine.
Conclusion
For the question about logging in to django admin, I did not have django.contrib.auth.backends.ModelBackend included in my AUTHENTICATION_BACKENDS - adding this allowed me to sign in to admin.
I'm still working on the django-admin.py configuration question (which appears to not be related), and will reopen it in a separate question.
In my case, I had "SESSION_COOKIE_SECURE = True" because I was trying SSL configurations. Just commenting this line worked.
Well, to answer one of your questions, the parent folder of mysite is what needs to be on the python path. Adding mysite itself to your python path will expose the contents of mysite, not the mysite module to python.
As for runserver working / passwords not working, I haven't a clue. Have you customized anything with authentication?
Can you start the shell and try authenticating with your superuser?
http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.authenticate
You said in a comment that "is_staff was set appropriately... same problem." -- does that mean you were able to log in with the first superuser to set is_staff??
I ran into a similair problem but, I couldn't login on the admin interface even after removing the database and creating it from scratch. The problem was caused by a real silly mistake.
Don't run python manage.py testserver by accident. Make sure you use python manage.py runserver.