I just deployed my sentiment analysis django app to heroku. The deployment was successful and I can access the features like login register etc. But I am unable to analyze the text because apparently, nltk cannot be found. But I have installed and imported it in my local host and it already worked before.
This is my first time deploying in heroku so I am unfamiliar with everything.
This is how it looks in my local host:
This is the error in the herokuapp live webapp when I try to analyze the sentiment.
LookupError at /sentiment/type/
**********************************************************************
Resource e[93mpunkte[0m not found.
Please use the NLTK Downloader to obtain the resource:
e[31m>>> import nltk
>>> nltk.download('punkt')
e[0m
For more information see: https://www.nltk.org/data.html
Attempted to load e[93mtokenizers/punkt/PY3/english.picklee[0m
Searched in:
- '/app/nltk_data'
- '/app/.heroku/python/nltk_data'
- '/app/.heroku/python/share/nltk_data'
- '/app/.heroku/python/lib/nltk_data'
- '/usr/share/nltk_data'
- '/usr/local/share/nltk_data'
- '/usr/lib/nltk_data'
- '/usr/local/lib/nltk_data'
- ''
**********************************************************************
Request Method: POST
Request URL: https://sentymeter.herokuapp.com/sentiment/type/
Django Version: 4.0
Exception Type: LookupError
Exception Value:
**********************************************************************
Resource e[93mpunkte[0m not found.
Please use the NLTK Downloader to obtain the resource:
e[31m>>> import nltk
>>> nltk.download('punkt')
e[0m
For more information see: https://www.nltk.org/data.html
Attempted to load e[93mtokenizers/punkt/PY3/english.picklee[0m
Searched in:
- '/app/nltk_data'
- '/app/.heroku/python/nltk_data'
- '/app/.heroku/python/share/nltk_data'
- '/app/.heroku/python/lib/nltk_data'
- '/usr/share/nltk_data'
- '/usr/local/share/nltk_data'
- '/usr/lib/nltk_data'
- '/usr/local/lib/nltk_data'
- ''
**********************************************************************
Exception Location: /app/.heroku/python/lib/python3.8/site-packages/nltk/data.py, line 583, in find
Python Executable: /app/.heroku/python/bin/python
Python Version: 3.8.9
Python Path:
['/app/.heroku/python/bin',
'/app',
'/app/.heroku/python/lib/python38.zip',
'/app/.heroku/python/lib/python3.8',
'/app/.heroku/python/lib/python3.8/lib-dynload',
'/app/.heroku/python/lib/python3.8/site-packages']
Server time: Wed, 05 Jan 2022 20:16:57 +0000
setting.py
"""
Django settings for sentiment_emotion_analysis project.
Generated by 'django-admin startproject' using Django 2.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sentiment.settings")
# import django
# django.setup()
# from django.core.management import call_command
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
messages.DEBUG: 'alert-debug',
messages.INFO: 'alert-info',
messages.SUCCESS: 'success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'danger',
}
# 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.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'g&x!0fjh8c8)e_-z#gs1^lbngvqwk2(o3s(5zg!o&woxdsu_un'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['sentymeter.herokuapp.com' , '127.0.0.1']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sentiment',
'user',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'sentiment_emotion_analysis.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "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 = 'sentiment_emotion_analysis.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/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.1/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.1/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.1/howto/static-files/
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
MODELS = os.path.join(BASE_DIR, 'sentiment/models')
Can anyone help me to solve this issue?
It looks like you installed the nltk python package but not any data for it.
If you want a quick fix, you can connect to your heroku (heroku ps:exec ) and run a django shell python manage.py shell and then install the relevant nltk modules from the python shell:
import nltk
nltk.download('punkt')
Since you want to be able to redeploy it, better create a management command to do this and run it similar to how you run migrations. Management command should be under {app}/management/commands/
A command like this:
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'Install NLTK stuff'
def handle(self, *args, **options):
import nltk
nltk.download(..) # replace the dots with the relevant corpora
Related
app/
├─ management/
│ ├─ commands/
│ │ ├─ customcommand.py
myfunction.py
site/
├─ settings.py
Content of settings.py
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 4.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/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',
'app'
]
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 = 'site.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 = 'site.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.1/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.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny'
]
}
Content of customcommand.py
from django.core.management.base import BaseCommand, CommandError
import time
import requests
class Command(BaseCommand):
help = 'Closes the specified poll for voting'
def handle(self, *args, **options):
print("execued the commands success!!")
start_time = time.time()
for number in range(1, 50):
url = f'https://pokeapi.co/api/v2/pokemon/{number}'
resp = requests.get(url)
pokemon = resp.json()
print(pokemon['name'])
print("--- %s seconds ---" % (time.time() - start_time))
Contents of myfunction.py
from django.core import management
def funcA():
management.call_command('customcommand')
funcA()
On calling myfunction.py from terminal it throws raise CommandError("Unknown command: %r" % command_name)
os.environ['DJANGO_SETTINGS_MODULE'] = 'site.settings'
Inside myfunction.py I have tried setting this, but it still doesn't work. Can someone help me out here, probably I am missing out on some important config
Try adding __init__.py to management/ and commands/ directories.
I have solved the issue by adding the django.setup() call, after configuring the environment variable.
Inside myfunction.py, the following changes should be made
from django.core import management
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'site.settings')
django.setup()
def funcA():
management.call_command('customcommand')
funcA()
django.setup() is essential to include because it registers your applications and commands defined in your settings in a standalone script which the manage.py or django-admin takes care usually
Hi I have finished my Django pycharm project and I'm now trying to upload it to heroku/ host it on heroku. I have followed this link https://medium.com/#qazi/how-to-deploy-a-django-app-to-heroku-in-2018-the-easy-way-48a528d97f9c which has actually successfully worked for me in the past. When I get to the step were you put this command in however 'heroku run python manage.py migrate' I continue to get this error message 'Running python manage.py migrate on ⬢ radiant-retreat-19016... up, run.6371 (Free)
python: can't open file 'manage.py': [Errno 2] No such file or directory'
Im not that much of a beginner so I know that my manage.py file is in the right place especially cause I can run ' python manage.py runserver '. I will attach the code to my procFile below along with my manage.py code and settings. I have looked everywhere on the internet for the problem and some people have it but nothing has worked for them. I will attach any other code if you need it. I even transferred all code to a new project and the same problem occurred.
web: gunicorn inspect_list2.wsgi
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'inspect_list2.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()
"""
Django settings for inspect_list project.
Generated by 'django-admin startproject' using Django 2.2.14.
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
import django_heroku
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
# 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 = 'not showing this but its there'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'my_app',
#'auth',
]
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 = 'inspect_list2.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'DIRS': [os.path.join(BASE_DIR, '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 = 'inspect_list2.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/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
AUTH_USER_MODEL = 'my_app.CustomUser'
LOGIN_REDIRECT_URL = 'front_page'
LOGOUT_REDIRECT_URL = 'home'
django_heroku.settings(locals())
Fixed by this
heroku run python **FOLDER**/manage.py migrate
ex
heroku run python HOME/manage.py migrate
I finally figured it out after 10 hours. Other sources online were right. If you refer to the link I posted above at the very bottom command. If you run the git push stuff first than that last command and after that you run the heroku migrate command it should work. WAIT! If it doesn't work then if you have touched your git repository stuff or changed the name or messed with your squilte3 file and you didn't know what you were doing then transfer all your code to another project so the git stuff and squilte3 stuff automatically is made and resets then follow the instruction in this comment again. If not I don't know what to tell you but it worked for me.
You can try this. Right click manage.py file and look for the option of open in terminal when it does run the code again
I am trying to use EEL + Django. i found this solution in this GitHub link.
I managed to make Django find the eel.js. but the issue it disconnect just after making WebSocket handshaking.
as below:-
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, content types, sessions.
Run 'python manage.py migrate' to apply them.
January 31, 2021 - 17:22:47
Django version 3.1.5, using settings 'demo.settings'
Starting ASGI/Channels version 3.0.0 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
HTTP GET /example/operations 200 [0.03, 127.0.0.1:57173]
HTTP GET /eel/eel.js 200 [0.01, 127.0.0.1:57173]
Not Found: /favicon.ico
HTTP GET /favicon.ico 404 [0.01, 127.0.0.1:57173]
WebSocket HANDSHAKING /eel [127.0.0.1:57177]
Exception inside application: object.__init__() takes exactly one argument (the instance to initialize)
Traceback (most recent call last):
File "D:\Python Projects\V1830Center\venv\lib\site-packages\channels\routing.py", line 71, in __call__
return await application(scope, receive, send)
File "D:\Python Projects\V1830Center\venv\lib\site-packages\channels\routing.py", line 160, in __call__
send,
File "D:\Python Projects\V1830Center\venv\lib\site-packages\asgiref\compatibility.py", line 33, in new_application
instance = application(scope)
File "D:\Python Projects\V1830Center\venv\lib\site-packages\channels\generic\websocket.py", line 23, in __init__
super().__init__(*args, **kwargs)
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
WebSocket DISCONNECT /eel [127.0.0.1:57177]
Project Tree:
Settings.py
"""
Django settings for demo project.
Generated by 'django-admin startproject' using Django 3.2a1.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-!d$idwr9=e0e82xi=78hjc0vhtfyh45r#)*(1#vt+dqzryips5'
# 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',
'channels',
'django_eel',
'example',
]
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 = 'demo.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 = 'demo.wsgi.application'
ASGI_APPLICATION = "demo.routing.application"
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/dev/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/dev/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/dev/howto/static-files/
STATIC_URL = 'example/assets/'
STATICFILES_DIRS=(
os.path.join(BASE_DIR,'example/templates/example/assets/'),
)
# Default primary key field type
# https://docs.djangoproject.com/en/dev/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
routing.py:
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url
from django_eel.consumers import EelConsumer
application = ProtocolTypeRouter({
# (http->django views is added by default)
"websocket": URLRouter([
url(r"^eel$", EelConsumer), # do not alter this line
]),
})
I wanted this solution to be able to use API + EEL methods together. so if anyone can help me with this problem. Thanks
I found solution for this problem,
that i added .as_asgi() to the routing.py file.
from channels.routing import ProtocolTypeRouter, URLRouter
from django.conf.urls import url
from django_eel.consumers import EelConsumer
application = ProtocolTypeRouter({
# (http->django views is added by default)
"websocket": URLRouter([
url(r"^eel$", EelConsumer.as_asgi()), # do not alter this line
]),
})
I created a simple django & react app (which just loads react default page for now) and I am trying to deploy to Heroku. When I run python manage.py runserver on localhost it runs fine (with default react page showing), but when I deploy it to Heroku, I get the following error:
TemplateDoesNotExist at /
index.html
This is the site : https://temp-app-test.herokuapp.com/
I'm pretty sure I included index.html in templates using os.path.join(BASE_DIR, 'build') in settings.py, but it doesn't work. I also included "postinstall": "npm run build" in scripts in package.json file.
requirements.txt
asgiref==3.2.7
Django==3.0.6
pytz==2020.1
sqlparse==0.3.1
whitenoise==5.0.1
gunicorn==20.0.4
runtime.txt
python-3.7.4
Procfile
release: python manage.py migrate
web: gunicorn test_test_test.wsgi --log-file -
settings.py
"""
Django settings for test_test_test project.
Generated by 'django-admin startproject' using Django 2.2.10.
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
# 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 = 'secret'
# 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',
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'test_test_test.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'build')],
'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 = 'test_test_test.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/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'build/static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
urls.py
from django.contrib import admin
from django.urls import path, re_path
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^.*', TemplateView.as_view(template_name='index.html'),
]
wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_test_test.settings')
application = get_wsgi_application()
I've been stuck here for hours, and I would like some help on this! Thanks in advance.
When I run a CMD Windows 7 command:
python manage.py makemigrations
I get an error:
django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql' isn't an available database backend. Try using 'django.db.backends.XXX' where XXX is one of : 'mysql', 'oracle', 'sqlite3'
I have installed postgresql 10, and in my django setting.py I have set the postgresql as per the documentation
I want to access postgresql database from python django app using CMD on Windows 7.
I'm using Windows 7, python 3.7.1; postgresql 10; django 2.1.5. I've tried several searches for solution but I do not get a relevant solution. I have already created my postgresql database using pgAdmin 4 v4 but it fails to be accessed using CMD command on Windows 7 to do commands like:
python manage.py showmigrations/makemigrations/migrate
all sends the same error as presented in the subject.
settings.py file starts here...
"""
Django settings for my_sample project.
Generated by 'django-admin startproject' using Django 2.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/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/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'secret key string was here but now is purposely removed'
# 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 = 'my_sample.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 = 'my_sample.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'my_sample',
'USER': 'postgres',
'PASSWORD': 'my_password',
'HOST':'localhost',
'PORT': '5432',
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/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.1/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.1/howto/static-files/
STATIC_URL = '/static/'
#settings.py file ends here...
#manage.py file starts here...
#!/usr/bin/env python
import os
import sys
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_sample.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)
#manage.py file ends here...
When I run:
python manage.py migrate
I expect to get:
Running migrations:
No migrations to apply.
Instead, I get:
django.core.exceptions.ImproperlyConfigured: 'django.db.backends.postgresql' isn't an available database backend. Try using 'django.db.backends.XXX' where XXX is one of : 'mysql', 'oracle', 'sqlite3'
Did you install the psycopg2 package? See https://docs.djangoproject.com/en/2.1/topics/install/#database-installation.
Or run pip install psycopg2
Add your app inside the INSTALLED_APPS list as below:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'yoursampleapp'
]
And then run makemigrations:
python manage.py makemigrations