Problem when trying to migrate command in Django app on Heroku server - python

I am currently trying to deploy my Django project on to a free Heroku server. When I try to execute the following command I get an error heroku run python3 manage.py migrate.
The error is as follows:
Running python3 manage.py makemigrations on ⬢ samstaskmanager... up, run.5214 (Free)
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 200, in connect
self.connection = self.get_new_connection(conn_params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
connection = Database.connect(**conn_params)
File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 85, in wrapped
res = handle_func(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle
loader.check_consistent_history(connection)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/loader.py", line 290, in check_consistent_history
applied = recorder.applied_migrations()
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations
if self.has_table():
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 55, in has_table
with self.connection.cursor() as cursor:
File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 259, in cursor
return self._cursor()
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 235, in _cursor
self.ensure_connection()
File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
self.connect()
File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 200, in connect
self.connection = self.get_new_connection(conn_params)
File "/app/.heroku/python/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection
connection = Database.connect(**conn_params)
File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 127, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
django.db.utils.OperationalError: could not connect to server: Connection refused
Is the server running on host "localhost" (127.0.0.1) and accepting
TCP/IP connections on port 5432?
This is my settings.py:
Django settings for app project.
Generated by 'django-admin startproject' using Django 3.1.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
#import django_heroku
# 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/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'x0)a5try9uyd+t_l-5x#1*yfu#-$-(u665rz5#_m!!t5b7&d(6'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'taskmanager.apps.TaskmanagerConfig',
'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 = 'app.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 = 'app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'taskmanager',
'USER': 'postgres',
'PASSWORD': 'sam3778987',
'HOST': 'localhost'
}
}
# Password validation
# https://docs.djangoproject.com/en/3.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/3.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/3.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# Activate Django-Heroku.
#django_heroku.settings(locals())
I am really not sure why I keep getting this error so any help would be appreciated. Also sorry about the messy question it is my first time writing one.

Looks to me like you are trying to use a PostgreSQL database on your local machine with your app hosted on Heroku.
I use a PostgreSQL database on a recently created app. I eventually created two settings.py files (with different names, obviously). One is what I use when I run the app locally. It has the following code for the database connection:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': DB_NAME,
'USER': MY_USERNAME,
'PASSWORD': MY_PASSWORD,
'HOST': HOST,
'PORT': '5432',
}
}
In my production settings.py (which I call settings_heroku_deploy.py and use in my Procfile during deployment) I have the following:
import dj_database_url
DATABASES = {}
DATABASES['default'] = dj_database_url.config(conn_max_age=600)
DATABASES['default']['ENGINE'] = 'django.db.backends.postgresql'
You probably know this already, but one of the characteristics of a PostgreSQL database is that it's hosted on a server. So the server you use needs to be available wherever you happen to run your application. I chose to configure a PostgreSQL database as an addon in Heroku. During deployment I use the dj_database_url package to automatically configure my connection, whereas on my local machine I have to explicitly provide username, password, etc.
Even if you can get your app to connect to your local database it's definitely worth making the switch a Heroku PostgreSQL database. It's free to start and certainly more flexible than hosting something locally (unless you have an actual server at your disposal).

It's due to your Postgres database.you can find it in the settings.py. change the host and port setting. maybe you have blank the host and port section. Let me know if it helps you.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'taskmanager',
'USER': 'postgres',
'PASSWORD': 'sam3778987',
'HOST': 'localhost',
'PORT': '5432',
}
}
edit: Thanks for sharing your settings.py code.
Let me know if it helps you.

Related

Error trying to migrate my database. Typing error

Sorry but I don't know what is happening when I try to run (python3 manage.py makemigrations).
I really don't know what's going on I'm looking for an answer for a while but I can't figure out where the error is:
(paginas) root#janstar:/home/paginas/proyectodedjango# python3 manage.py makemigrations
Traceback (most recent call last):
File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped
res = handle_func(*args, **kwargs)
File "/home/paginas/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 101, in handle
loader.check_consistent_history(connection)
File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/loader.py", line 283, in check_consistent_history
applied = recorder.applied_migrations()
File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 76, in applied_migrations
if self.has_table():
File "/home/paginas/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 56, in has_table
return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 260, in cursor
return self._cursor()
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 236, in _cursor
self.ensure_connection()
File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection
self.connect()
File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/base/base.py", line 197, in connect
self.connection = self.get_new_connection(conn_params)
File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 199, in get_new_connection
conn = Database.connect(**conn_params)
TypeError: argument 1 must be str, not PosixPath
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
main()
File "manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/home/paginas/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/home/paginas/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/paginas/lib/python3.6/site-packages/django/core/management/base.py", line 341, in run_from_argv
connections.close_all()
File "/home/paginas/lib/python3.6/site-packages/django/db/utils.py", line 230, in close_all
connection.close()
File "/home/paginas/lib/python3.6/site-packages/django/utils/asyncio.py", line 26, in inner
return func(*args, **kwargs)
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 261, in close
if not self.is_in_memory_db():
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 380, in is_in_memory_db
return self.creation.is_in_memory_db(self.settings_dict['NAME'])
File "/home/paginas/lib/python3.6/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db
return database_name == ':memory:' or 'mode=memory' in database_name
TypeError: argument of type 'PosixPath' is not iterable
Try changing this:
For this:
Sorry if I added the images wrong I'm new to this page.
This is my settings.py file:
"""
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/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-k3d35^_5m3-=t-7&-!4qq78o+h%-ra6atz-a9m1)19a7()$8u2'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['31.220.48.123']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ckeditor',
'mainapp',
'pages.apps.PagesConfig',
'blog.apps.BlogConfig',
]
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 = 'ProyectoDjango.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',
'pages.context_processors.get_pages',
'blog.processor.get_categories',
],
},
},
]
WSGI_APPLICATION = 'ProyectoDjango.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",
}
}
"""
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
"""
"""
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'proyectodjango',
'USER': 'root',
'PASSWORD': '12345',
'HOST': 'localhost',
'PORT': 3306
}
}
"""
# 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 = 'es-es'
TIME_ZONE = 'UTC'
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'
# Media
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
"""
and this is my manage.py file:
enter image description here
In the error message it says that you need a string instead of 'PosixPath' try turning the path into a string.
You can also use:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
Simply you can try this way:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
After adding above code in settings.py file, first you need to delete db file and delete all migration folders of each app and then run below commands:
python manage.py makemigrations appname
python manage.py sqlmigrate appname 0001
python manage.py migrate
And now your problem will solve.

Intellj python test: run individual Django tests

I have Django application inside IntelliJ IDE.
I can run all Django tests by calling the Django Tests runner.
But:
This is a time consuming and not ideal for development, where you would like to rerun one test that fail, and not run all 1000 others that are ok.
IntelliJ has options (UI) to run one test quickly, but this run python tests runner.
I add DJANGO_SETTINGS_MODULE=... inside, but now I get other errors:
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
I was looking to solve this error and I only found :
import django
django.setup()
inside Settings.py
My problem with this is:
I think this breaks normal behaviour of the app. App works normal for different environments.
It doesn't call code after this setup inside settings, so secret_key and others are not installed
This doesn't seam to be really related to tests, but is changing the whole app.
So, I am looking for some settings, how to set the normal python tests, so that they will run as django tests.
EDIT:
Now I change some thinks around and do:
Separate Settings for test
Do all the imports and then django.setup()
Now I get different error:
# The settings_test.py
SECRET_KEY = 'kdbaskdbkjadasd'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mobileapp',
]
DEBUG = True
ALLOWED_HOSTS = '*'
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',
]
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 = '...wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '...',
'USER': '...',
'PASSWORD': '...',
'HOST': 'localhost',
'PORT': 5432,
}
}
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',
},
]
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
import django
django.setup()
error:
/Users/zadravecm/Work/.../env/bin/python3.6 /Users/zadravecm/Work/.../tests/tests.py
Traceback (most recent call last):
File "/Users/zadravecm/Work/.../tests/tests.py", line 2, in <module>
from ....Services import subsidiary_service as sub_service
File "/Users/zadravecm/Work/.../Services/subsidiary_service.py", line 3, in <module>
from ....models import *
File "/Users/zadravecm/Work/.../models.py", line 2, in <module>
from django.contrib.auth.models import User
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module>
class AbstractBaseUser(models.Model):
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/db/models/base.py", line 107, in __new__
app_config = apps.get_containing_app_config(module)
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/apps/registry.py", line 252, in get_containing_app_config
self.check_apps_ready()
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/apps/registry.py", line 134, in check_apps_ready
settings.INSTALLED_APPS
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__
self._setup(name)
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup
self._wrapped = Settings(settings_module)
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/conf/__init__.py", line 142, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/Users/zadravecm/Work/.../env/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/Users/zadravecm/Work/.../settings_test.py", line 121, in <module>
django.setup()
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/apps/registry.py", line 122, in populate
app_config.ready()
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/contrib/admin/apps.py", line 24, in ready
self.module.autodiscover()
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
autodiscover_modules('admin', register_to=site)
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules
import_module('%s.%s' % (app_config.name, module_to_search))
File "/Users/zadravecm/Work/.../env/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/Users/zadravecm/.../env/lib/python3.6/site-packages/django/contrib/auth/admin.py", line 6, in <module>
from django.contrib.auth.forms import (
File "/Users/zadravecm/Work/.../env/lib/python3.6/site-packages/django/contrib/auth/forms.py", line 10, in <module>
from django.contrib.auth.models import User
ImportError: cannot import name 'User'
EDIT:
The image of the settings of a test runner that is run automatically, if I click run icon on tests.

Django settings not working correctly

I am able to execute
python manage.py migrate - it executes perfectly
But when I run
django-admin shell
it fails giving the following errors
Traceback (most recent call last):
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/base.py", line 337, in execute
saved_locale = translation.get_language()
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/utils/translation/__init__.py", line 190, in get_language
return _trans.get_language()
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/utils/translation/__init__.py", line 57, in __getattr__
if settings.USE_I18N:
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 39, in _setup
% (desc, ENVIRONMENT_VARIABLE))
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.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/cj/.vtenv/officingx/bin/django-admin", line 11, in <module>
sys.exit(execute_from_command_line())
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/core/management/base.py", line 306, in run_from_argv
connections.close_all()
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/db/utils.py", line 229, in close_all
for alias in self:
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/db/utils.py", line 223, in __iter__
return iter(self.databases)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/utils/functional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/db/utils.py", line 156, in databases
self._databases = settings.DATABASES
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/home/cj/.vtenv/officingx/lib/python3.5/site-packages/django/conf/__init__.py", line 39, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
My settings.py
"""
Django settings for officingx project.
Generated by 'django-admin startproject' using Django 1.10.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
import dj_database_url
# 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.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['OFFICINGX_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',
'amenity.apps.AmenityConfig',
'booking.apps.BookingConfig',
'location.apps.LocationConfig',
'organization.apps.OrganizationConfig',
'photo.apps.PhotoConfig',
'product.apps.ProductConfig',
'property.apps.PropertyConfig',
]
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 = 'officingx.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 = 'officingx.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {'default': dj_database_url.config()}
# Password validation
# https://docs.djangoproject.com/en/1.10/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.10/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.10/howto/static-files/
STATIC_URL = '/static/'
Please help I can't understand why its not able read the settings even when migrate command is working perfectly fine
Taken from the docs:
Generally, when working on a single Django project, it’s easier to use manage.py than django-admin. If you need to switch between multiple Django settings files, use django-admin with DJANGO_SETTINGS_MODULE or the --settings command line option.
You didn't specify a --settings module (as an argument) in the django-admin, that's why Django complains. Do it like this: django-admin shell --settings=myproject.settings.
Also, from the docs:
The settings module should be in Python package syntax, e.g. mysite.settings. If this isn’t provided, django-admin will use the DJANGO_SETTINGS_MODULE environment variable.
You can also do ./manage.py shell

not able to run manage.py runserver

Below is the problem i am facing while running the server.
I'm not able to start manage.py runserver . I'm Using sqlite3 database. I am trying to run quite basic application. system configurations: windows 10, python 2.7.
Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.
C:\Users\rutwi_000>cd C:\Python27\Scripts\mysite
C:\Python27\Scripts\mysite>C:/Python27/python manage.py runserver
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 350, in execute_from_command_line
utility.execute()
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 195, in fetch_command
klass = load_command_class(app_name, subcommand)
File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 39, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Python27\lib\site-packages\django\core\management\commands\runserver.py", line 16, in <module>
from django.db.migrations.executor import MigrationExecutor
File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 7, in <module>
from .loader import MigrationLoader
File "C:\Python27\lib\site-packages\django\db\migrations\loader.py", line 10, in <module>
from django.db.migrations.recorder import MigrationRecorder
File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 12, in <module>
class MigrationRecorder(object):
File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 26, in MigrationRecorder
class Migration(models.Model):
File "C:\Python27\lib\site-packages\django\db\migrations\recorder.py", line 27, in Migration
app = models.CharField(max_length=255)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 1072, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 166, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 55, in __getattr__
self._setup(name)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 43, in _setup
self._wrapped = Settings(settings_module)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 99, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
__import__(name)
File "C:\Python27\Scripts\mysite\mysite\settings.py", line 15, in <module>
django.setup()
File "C:\Python27\lib\site-packages\django\__init__.py", line 17, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 55, in __getattr__
self._setup(name)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 43, in _setup
self._wrapped = Settings(settings_module)
File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 120, in __init__
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
Please help me with this question. Thanks!!!!!!
Below is the settings.py file.
Note: I do have a security key (not shown in the code below)
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.9.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
import django
django.setup()
# 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.9/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 = [
'personal',
'blog',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.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 = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/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.9/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.9/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.9/howto/static-files/
STATIC_URL = '/static/'
Your error traceback clearly states that your SECRET_KEY is empty
raise ImproperlyConfigured("The SECRET_KEY setting must not be
empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
Generate a new one, you can use this
"""
Pseudo-random django secret key generator.
- Does print SECRET key to terminal which can be seen as unsafe.
"""
from __future__ import print_function
import string
import random
# Get ascii Characters numbers and punctuation (minus quote characters as they could terminate string).
chars = ''.join([string.ascii_letters, string.digits, string.punctuation]).replace('\'', '').replace('"', '').replace('\\', '')
SECRET_KEY = ''.join([random.SystemRandom().choice(chars) for i in range(50)])
print(SECRET_KEY)
save this in secret_key.py file, and do python secret_key.py, it will generate you a new SECRET KEY, then just copy new SECRET_KEY inside you're settings.py file.

TypeError: unhashable type: 'bytearray'

I'm new to django and trying to create a Homepage. But I've already problems with the database setup. When I run
python manage.py migrate
I get this error
(env) paul#Kreker-Server:~/public_html/p_kreker$ python manage.py migrate
Operations to perform:
Apply all migrations: auth, sessions, contenttypes, admin
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying sessions.0001_initial... OK
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 165, in handle
emit_post_migrate_signal(created_models, self.verbosity, self.interactive, connection.alias)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/sql.py", line 268, in emit_post_migrate_signal
using=db)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/dispatch/dispatcher.py", line 198, in send
response = receiver(signal=self, sender=sender, **named)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/contrib/auth/management/__init__.py", line 64, in create_permissions
if not is_latest_migration_applied('auth'):
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/db/migrations/loader.py", line 292, in is_latest_migration_applied
loader = MigrationLoader(connection)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/db/migrations/loader.py", line 49, in __init__
self.build_graph()
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/db/migrations/loader.py", line 184, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/db/migrations/recorder.py", line 60, in applied_migrations
return set(tuple(x) for x in self.migration_qs.values_list("app", "name"))
TypeError: unhashable type: 'bytearray'
I'm using python-3.4, django-1.7.4 and for the SQL connection mysql-connector-python-2.0.2. For this project I've created a virtual environment with the python 3 venv. I host this project on github: https://github.com/pkreker/p_kreker
Thank you in advance!
edit settings.py:
"""
Django settings for p_kreker project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '#l)bvja#q45ud2d813g*i+n2=1#kbf#nzqm6()c)dv116pqq^p'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_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_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'p_kreker.urls'
WSGI_APPLICATION = 'p_kreker.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases
DATABASES = {
'default': {
'NAME': 'p_kreker',
'ENGINE': 'mysql.connector.django',
'USER': 'paul',
'PASSWORD': 'm2aJup2fHYDdArGT',
'OPTIONS': {
'autocommit': True,
},
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/
LANGUAGE_CODE = 'de-de'
TIME_ZONE = 'Europe/Berlin'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
Since the bug headline does not specify "Django", I expect a number of Python 3 newbies will end up here. Note that the hashable/immutable counterpart to "bytearray" is the type "bytes".
>>> b1 = bytearray([1, 2, 3])
>>> s = set()
>>> s.add(b1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'bytearray'
>>> b2 = bytes(b1)
>>> b2
b'\x01\x02\x03'
>>> s.add(b2)
>>>
I think this is likely to be a bug in mysql-connector-python - does it support Django 1.7.4? Your code works fine if you run it with sqlite.
If the project is on an older version of Django for example 1.11.16, try explicit decoding by calling the method .decode("utf-8") in introspection.py file.
if django.VERSION >= (1, 8):
return [
TableInfo(row[0].decode("utf-8"), {'BASE TABLE': 't', 'VIEW': 'v'}.get(row[1].decode("utf-8")))
for row in cursor.fetchall()
]
else:
return [row[0] for row in cursor.fetchall()]
introspection.py file path:
C:\Python27\Lib\site-packages\mysql\connector\django\introspection.py
method prototype:
def get_table_list(self, cursor):
I had this error today. I had created my db as utf8_bin collation, which I assume was the reason for it. Dropped the DB, re-created with utf8_general_ci, ran migrations, and it worked fine.

Categories