Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have a file to fetch info from a API (UK Company House). To test I have
import requests
r = requests.get('https://api.companieshouse.gov.uk/company/00002065', auth=('xxxxx', ''))
print(r.text)
It works and produces the data, but then after the data I get the following error message
AttributeError: module 'app.management.commands.api' has no attribute
'Command'
Why is this and how do I resolve?
Edit - Additionally, if I run "py ch_api.py" in the same folder the file is located it works with no error; only when I run "py manage.py ch_scrape" I get the error (I need to run it through the second method)
Edit 2 - Some further info
Files
project
├── __init__.py
├── manage.py
├── fetches
├── management
├── __init__.py
├── commands
├── ch_api.py
├── __init__.py
└── project
├── __init__.py
├── asgi.py
├── settings.py
├── urls.py
├── views.py
├── wsgi.py
My manage.py file
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
My settings.py file
"""
Django settings for project project.
Generated by 'django-admin startproject' using Django 3.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*******'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'project.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR,'assets'),
)
Ok - got it. Coming from Rails, I'm not sure what or why Command(BaseCommand) is required, but learning as I go. If anyone wants to pop a small nudge to what this is all about, it would be appreciated.
from django.core.management.base import BaseCommand, CommandError
import requests
class Command(BaseCommand):
def handle(self, *args, **options):
r = requests.get('https://api.companieshouse.gov.uk/company/00002065', auth=('DKvKM78qjU0Er_PGYnAdfSpgNquuz9LA_GYp1KNY', ''))
print(r.text)
Related
I have deployed my Django online judge project on AWS EC2 using Nginx and Gunicorn I am taking user code in a string variable and writing it to a file in my project directory and it's working fine in development server but after deployment the program unable to write code in the file. for eg:-
lets say a user have submitted code in c++ language so I took that code in a string variable and I open the my .cpp file via open() function in my views.py and writing the code in it.
filepath = os.path.join(settings.BASE_DIR, 'language', 'forcpp.cpp')
cpp_code=open(filepath,"w")
cpp_code.write(user_problem_code)
cpp_code.close()
I have tried to modify path in every possible way but got unlucky in every try
I have my files in language folder in which I want to write user submitted code and my views.py are in problempg application
my project directory structure:
online_judge_project/
account/
homesrc/
language/ /* directory containing files in which I want to write */
forcpp.cpp
media/
oj/
settings.py
problempg/ /* application containing views.py */
views.py
static/
staticfiles/
template/
manage.py
settings.py
"""
Django settings for oj project.
Generated by 'django-admin startproject' using Django 4.0.5.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from importlib.resources import path
from pathlib import Path
import os
from .info import *
EMAIL_USE_TLS = EMAIL_USE_TLS
EMAIL_HOST = EMAIL_HOST
EMAIL_HOST_USER = EMAIL_HOST_USER
EMAIL_HOST_PASSWORD = EMAIL_HOST_PASSWORD
EMAIL_PORT = EMAIL_PORT
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR=os.path.join(BASE_DIR,'template')
FILES_DIR=os.path.abspath(os.path.join(BASE_DIR,'language'))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["localhost","<MY_IP_ADDRESS>"]
# Application definition
INSTALLED_APPS = [
'widget_tweaks',
'account.apps.AccountConfig',
'problempg.apps.ProblempgConfig',
'homescr.apps.HomescrConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ckeditor',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'oj.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'oj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_ROOT= os.path.join(BASE_DIR,'staticfiles')
STATIC_URL = 'static/'
MEDIA_ROOT= os.path.join(BASE_DIR,'media')
MEDIA_URL='/media/'
LOGOUT_REDIRECT_URL = "index"
STATICFILES_DIRS=[
os.path.join(BASE_DIR, 'static'),
]
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
messages.DEBUG: 'alert-info',
messages.INFO: 'alert-info',
messages.SUCCESS: 'alert-success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'alert-danger',
}
may be the path I am using in development is different in EC2 server. I have develop this project on a windows machine and I am deploying it on Ubantu EC2 server or it's due to Nginx?
I have a Django project called Veganet that I am trying to run, but when I run my main script vega_flask_run.py it gives me an improperly configured error. The source of the error is coming from a script named models.py, more specifically line 2 where I am declaring from django.contrib.auth.models import User. I have tried to use a few posts to solve my problem including:
I have tried solutions like changing the INSTALLED_APPS variable in my projects settings.py and changing the DATABASES variable inside settings.py, as well as using Windows Powershell to execute python manage.py shell, django-admin.py shell --settings=mysite.settings, and then setting the DJANGO_SETTINGS_MODULE variable to point to my projects settings and lastly using
from django.core.management import setup_environ
from veganet import settings
setup_environ(settings)
here is the error in it's entirety:
Exception has occurred: ImproperlyConfigured
Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
File "C:\Users\trevo\OneDrive\Desktop\veganet\profiles\models.py", line 2, in <module>
from django.contrib.auth.models import User
File "C:\Users\trevo\OneDrive\Desktop\veganet\profiles\forms.py", line 2, in <module>
from .models import ExperimentContext, Profile
File "C:\Users\trevo\OneDrive\Desktop\veganet\vega_ai\VegaMain.py", line 25, in <module>
from profiles.forms import ProfileModelForm, ExperimentModelForm
File "C:\Users\trevo\OneDrive\Desktop\veganet\vega_flask_run.py", line 5, in <module>
from vega_ai.VegaMain import app as frontend
Here is my simplified file structure:
veganet (main folder)
-profiles (folder)
...
models.py (script that gives me the error)
signals.py
urls.py
utils.py
views.py
-vega_ai (folder)
VegaMain.py
...
-vega_net (folder)
...
asgi.py
settings.py
urls.py
views.py
wsgi.py
db.sqlite3
manage.py
vega_flask_run.py (where I am running the project)
my settings.py file:
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-p8!i$5eqn)l(f0(n##1yntb^#ctfm3u*)j9xrjy^(1n9s&jdsa'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'posts',
'profiles',
'veganet',
]
LOGIN_URL = '/admin/'
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'veganet.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ["C:/Users/trevo/OneDrive/Desktop/veganet/templates"],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'veganet.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static_project')
]
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn", "static_root")
MEDIA_URL = '/media/'
MEDIA_ROOT = 'C:/Users/trevo/OneDrive/Desktop/veganet/static_cdn/media_root'
my wsgi.py script:
import os
from django.conf import settings
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'veganet.settings')
application = get_wsgi_application()
models.py
from django.db import models
from django.contrib.auth.models import User
from django.dispatch.dispatcher import receiver
from .utils import get_random_code
from django.template.defaultfilters import slugify
import subprocess
...
vega_flask_run.py
from email.mime import application
from flask import Flask, render_template
from werkzeug.serving import run_simple
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from vega_ai.VegaMain import app as frontend
from manage import app as backend
from werkzeug.exceptions import NotFound
app = Flask(__name__, template_folder="C:/Users/trevo/OneDrive/Desktop/veganet/profiles/templates/profiles", static_folder="C:/Users/trevo/OneDrive/Desktop/veganet/static_project")
app.wsgi_app = DispatcherMiddleware(frontend, {
'/app2':app,
'/app3':backend
})
if __name__ == '__main__':
app.run(debug=True,port=8080,use_reloader=False)
What exactly am I missing here? Thank you
If this is Django, and not flask as the vega_flask_run.py name implies then you need to run python manage.py runserver to start the application.
This might be a duplicate of Django ImproperlyConfigured for import User.
Also, models.py is not a script your run in django in the manner I think you're saying. It is where the models you define, the classes, for your project are located.
I may be the one missing something. Maybe you can edit your question with the vega_flask_run.py file. Perhaps you're using it in a way that I'm just not familiar with.
Otherwise, I suggest you start with https://docs.djangoproject.com/en/4.0/intro/tutorial01/. I mean it looks like you've already started the project correctly since you have the django files there. Maybe it's just a matter of how you start them.
Edit
Yes, now I can see that you're trying to run a djagno app as if it were a flask app, app = Flask(__name__, .... Despite both Flask and Django being python frameworks, they are run very differently.
I am using Django 3.0 for my project and want to make a simple registration page. My registration information is not showing up on the admin database page. python manage.py runserver is not raising any errors but admin.py and views.py have import errors. I'm also sharing same code snippet. Here are some snippet of my admin.py, views.py, models.py and settings.py.
error
[Running] python -u "g:\Study\Python\Django Project\checkproject\checkapp\views.py"
Traceback (most recent call last):
File "g:\Study\Python\Django Project\checkproject\checkapp\views.py", line 3, in <module>
from .models import registerPerson
ImportError: attempted relative import with no known parent package
admin.py
from django.contrib import admin
from .models import registerPerson
class register(admin.ModelAdmin):
list_display = ['firstname', 'lastname', 'email', 'password']
admin.site.register(registerPerson,register)
views.py
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import registerPerson
def register(request):
return render(request,'registration.html')
def add_registration(request):
firstname = request.POST["first_name"]
lastname = request.POST["lastname"]
email = request.POST["email"]
password = request.POST["password"]
info = registerPerson(firstname=firstname, lastname=lastname, email=email, password=password)
info.save()
return render(request,'registration.html')
models.py
from django.db import models
# Create your models here.
class registerPerson(models.Model):
firstname=models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
email = models.CharField(max_length=30)
password = models.CharField(max_length=32)
def __str__(self):
return self.firstname
settings.py
["""
Django settings for checkProject project.
Generated by 'django-admin startproject' using Django 3.0.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATES_DIR=os.path.join(BASE_DIR,'checkapp/templates')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '6rst-p=7+k*hq*21uynw_rj)=s2iqh668_hun-vg7+!##uni9o'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = \[\]
# Application definition
INSTALLED_APPS = \[
'checkapp.apps.CheckappConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
\]
MIDDLEWARE = \[
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
\]
ROOT_URLCONF = 'checkProject.urls'
TEMPLATES = \[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': \[TEMPLATES_DIR\],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': \[
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
\],
},
},
\]
WSGI_APPLICATION = 'checkProject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = \[
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
\]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
here is my project tree structure
CHECKPROJECT
checkapp
_pycache
migrations
templates
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
checkProject
__pycache__
__init__.py
asgi.py
settings.py
urls.py
wsgi.py
db.sqlite3
manage.py
I keep getting this error when i try to import my models.py file into views.py or any of the other python script in my App directory,
I have the SECRET_KEY in settings.py and also add app in the list of INSTALLED_APPS,
wsgi.py contains
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings') # I replaced my project name
manage.py also contains
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings')
I have checked through other people's installations in StackOverflow posts. My code works but importing models just break it
I use this command to import my class
from app_name.models import subscribers
and subscribers is defined thus
class subscribers(models.Model):
name = models.CharField('Name', max_length=120)
email = models.CharField('Email', max_length=120)
access_token = models.TextField()
expires_in = models.DateTimeField('token expiry date')
I have already executed makemigrations and migrate commands but being a newbie I don't know where else to look. Please save a soul it's been 3 days
thanks.
below is my settings.py
"""
Django settings for ps project.
Generated by 'django-admin startproject' using Django 2.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
from oauth_outlook.views import gettoken
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY='l!u#h#an5lj%b))=fzhv6r-3ay1&29=ls0*o1_^dxi(01x$et#'
#SECRET_KEY = os.environ.get("SECRET_KEY", "l!u#h#an5lj%b))=fzhv6r-3ay1&29=ls0*o1_^dxi(01x$et#")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'oauth_outlook',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'lockdown.middleware.LockdownMiddleware',
]
ROOT_URLCONF = 'ps.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'ps.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
MEDIA_URL = 'media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
LOCKDOWN_PASSWORDS = ('letmein', 'beta')
LOCKDOWN_VIEW_EXCEPTIONS = [
gettoken,
]
It looks like the following import is causing the problem:
from oauth_outlook.views import gettoken
Importing views or models in the settings can cause circular imports and lead to the SECRET_KEY error message even when it is set. I don’t like the way django-lockout is encouraging you to import views for the LOCKDOWN_VIEW_EXCEPTIONS setting.
I suggest you set LOCKDOWN_URL_EXCEPTIONS instead, then the import isn’t required.
LOCKDOWN_URL_EXCEPTIONS = (
r'^gettoken$', # replace with gettoken view
)
While running command - python manage.py test --settings=todobackend.settings.test
from terminal inside virtualenv I get the error ImportError: No module named base
I'm running python 2.7
and Django 1.9.0
Hierarchy
todobackend
settings
base.py
test.py
manage.py
test.py
from base import *
import os
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': os.environ.get('MYSQL_DATABASE', 'todobackend'),
'USER': os.environ.get('MYSQL_USER', 'todo'),
'PASSWORD': os.environ.get('MYSQL_PASSWORD', 'password'),
'HOST': os.environ.get('MYSQL_HOST', 'localhost'),
'PORT': os.environ.get('MYSQL_PORT', '3306')
}
}
base.py
"""
Django settings for todobackend project.
Generated by 'django-admin startproject' using Django 1.11.20.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'YOUR_SECRET_KEY'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'todos'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'todobackend.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'todobackend.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
# CORS Settings
CORS_ORIGIN_ALLOW_ALL = True
manage.py
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE",
"todobackend.settings.base")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
You settings folder is not a Python package, you must add a file named __init__.py to that folder.
You do not have 'base' in your INSTALLED_APPS which is what Django looks for when you just import base in your test.py file.
On top of this, the later versions of Python seem to really prefer the full import path rather than relative ones and can throw an error if this is not used.
To fix this, just add:
//test.py
from todobackend.settings.base import *
I hope this helps!