Intellj python test: run individual Django tests - python

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.

Related

Why does my Environ import doesn't import .env variables?

I'm building a Django app but I've got an issue. I've imported the environ package in order to store all my variables in a .env file, but actually it seems my app doesn't read it and I can't get why.
Here is my .env file:
DEBUG=True
SECRET_KEY='<SECRET>'
DB_NAME=<SECRET>
DB_USER=<SECRET>
DB_PASSWORD=<SECRET>
DB_HOST=localhost
DB_PORT=
EMAIL_HOST=
EMAIL_HOST_USER=
EMAIL_HOST_PASSWORD=
EMAIL_PORT=
DEFAULT_FROM_EMAIL=<SECRET>
Here is my settings.py file:
from pathlib import Path
import environ
env = environ.Env(
DEBUG=(bool, False)
)
READ_DOT_ENV_FILE = env.bool('READ_DOT_ENV_FILE', default=False)
if READ_DOT_ENV_FILE:
environ.Env.read_env()
DEBUG = env('DEBUG')
SECRET_KEY = env('SECRET_KEY')
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third party apps
'crispy_forms',
'crispy_tailwind',
'tailwind',
'theme',
# Local apps
'leads',
'agents',
]
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
'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 = 'djcrm.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ 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 = 'djcrm.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': env("DB_NAME"),
'USER': env("DB_USER"),
'PASSWORD': env("DB_PASSWORD"),
'HOST': env("DB_HOST"),
'PORT': env("DB_PORT"),
}
}
# 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/'
STATICFILES_DIRS = [
BASE_DIR / "static"
]
MEDIA_URL = '/media/'
MEDIA_ROOT = "media_root"
STATIC_ROOT = "static_root"
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
AUTH_USER_MODEL = 'leads.User'
EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
LOGIN_REDIRECT_URL = "/leads"
LOGIN_URL = "/login"
LOGOUT_REDIRECT_URL = "/"
CRISPY_ALLOWED_TEMPLATE_PACKS = "tailwind"
CRISPY_TEMPLATE_PACK = 'tailwind'
if not DEBUG:
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_CONTENT_TYPE_NOSNIFF = True
SECURE_HSTS_SECONDS = 31536000 # 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
X_FRAME_OPTIONS = "DENY"
ALLOWED_HOSTS = ["*"]
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = env("EMAIL_HOST")
EMAIL_HOST_USER = env("EMAIL_HOST_USER")
EMAIL_HOST_PASSWORD = env("EMAIL_HOST_PASSWORD")
EMAIL_USE_TLS = True
EMAIL_PORT = env("EMAIL_PORT")
DEFAULT_FROM_EMAIL = env("DEFAULT_FROM_EMAIL")
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
'level': 'WARNING',
},
}
TAILWIND_APP_NAME = 'theme'
When I run the python manage.py runserver command (or any other command btw), I get this error:
Traceback (most recent call last):
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/environ/environ.py", line 273, in get_value
value = self.ENVIRON[var]
File "/opt/homebrew/Cellar/python#3.9/3.9.2_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 679, in __getitem__
raise KeyError(key) from None
KeyError: 'SECRET_KEY'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/davidemancuso/Dev/django-crm/manage.py", line 22, in <module>
main()
File "/Users/davidemancuso/Dev/django-crm/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 61, in execute
super().execute(*args, **options)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 68, in handle
if not settings.DEBUG and not settings.ALLOWED_HOSTS:
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/conf/__init__.py", line 83, in __getattr__
self._setup(name)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/conf/__init__.py", line 70, in _setup
self._wrapped = Settings(settings_module)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/django/conf/__init__.py", line 177, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/opt/homebrew/Cellar/python#3.9/3.9.2_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 790, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "/Users/davidemancuso/Dev/django-crm/djcrm/settings.py", line 13, in <module>
SECRET_KEY = env('SECRET_KEY')
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/environ/environ.py", line 123, in __call__
return self.get_value(var, cast=cast, default=default, parse_default=parse_default)
File "/Users/davidemancuso/Dev/django-crm/env/lib/python3.9/site-packages/environ/environ.py", line 277, in get_value
raise ImproperlyConfigured(error_msg)
django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable
Now, if I put the secret key hard-coded into the settings.py, the error changes in:
django.core.exceptions.ImproperlyConfigured: Set the DB_NAME environment variable
As far as I can see, it seems the settings.py is not reading at all the variables in the .env, but I don't know how to solve this. What can I do?
EDIT: PROBLEM SOLVED
It was easier than I thought. I forgot to type in the terminal export READ_DOT_ENV_FILE=True in order to enable the file reading in development.
Thanks to all who try to help me!
Have a nice day
PROBLEM SOLVED
It was easier than I thought. I forgot to type in the terminal export READ_DOT_ENV_FILE=True in order to enable the file reading in development.
Thanks to all who try to help me!
Have a nice day
Make sure that your .env file is in the same directory as your settings.py.
This may be a hard way
Try following code for every variable in the console
export SECRET_KEY='<SECRET>'

Django settings module exception

I got the following error:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\pydevd.py", line 1741, in <module>
main()
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\pydevd.py", line 1735, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\pydevd.py", line 1135, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Apache24/htdocs/consult/accounts/models.py", line 7, in <module>
from django.contrib.auth.models import AbstractUser
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\contrib\auth\models.py", line 2, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module>
class AbstractBaseUser(models.Model):
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\db\models\base.py", line 87, in __new__
app_config = apps.get_containing_app_config(module)
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\apps\registry.py", line 249, in get_containing_app_config
self.check_apps_ready()
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\apps\registry.py", line 131, in check_apps_ready
settings.INSTALLED_APPS
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\conf\__init__.py", line 57, in __getattr__
self._setup(name)
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\conf\__init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.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.
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.1.1\helpers\pydev\_pydevd_bundle\pydevd_xml.py", line 179, in _get_type
if isinstance(o, t[0]):
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\utils\functional.py", line 213, in inner
self._setup()
File "C:\Apache24\htdocs\consult\clinicenv\lib\site-packages\django\conf\__init__.py", line 42, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested settings, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
I am very new to Python programming. Please help me to resolve this and let me know how to set PYTHON ENVIRONMENT VARIABLE.
this is my settings.py
INSTALLED_APPS =
[
'accounts',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_mysql',
]
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 = 'consult.urls'
TEMPLATES =
[
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['/templates/accounts/'],
'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 = 'consult.wsgi.application'
DATABASES =
{
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'suitecaredb',
'USER': 'root',
'PASSWORD': 'innovations',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
'charset': 'utf8mb4',
},
'TEST': {
'CHARSET': 'utf8mb4',
'COLLATION': 'utf8mb4_unicode_ci',
}
}
}
AUTH_USER_MODEL = "accounts.User"
To open a python terminal with the Django environment set run
python manage.py shell
Then, for example, a new user can be created with the create_user() helper function:
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('john', 'lennon#thebeatles.com', 'johnpassword')
# At this point, user is a User object that has already been saved
# to the database. You can continue to change its attributes
# if you want to change other fields.
>>> user.last_name = 'Lennon'
>>> user.save()
The example code below shows how to add a user from a script. Note that you need to replace 'project.settings' on line 2 with your project name.
project.setting points at your project file where installed apps, middleware, templates, etc are specified.
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE','project.settings')
import django
django.setup()
from django.contrib.auth.models import User
super_user = User.objects.create_user(username = 'john',
first_name = 'John',
last_name = 'Doe',
email = 'john.doe#mail.com',
password = 'test',
is_staff = True,
is_superuser=True
)
More information in the documentation docs.djangoproject.com
On setting:
wsgi.py
Check if it is pointing to the right setting path:
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "path/to/settings.py")
Try out the following:
As mentioned in the above answer, ensure that the following line is present in wsgi.py
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "/path/to/settings.py")
Ensure that above path is correct or the mentioned settings file in above line is the actual settings file.
Since you are using Pycharm, the above error could because cause of some issue with the Pycharm environment variable. Try python manage.py flush.
If the issue still persists, have a look at the environment configuration in the Pycharm settings and check for any discrepancy.

OSError in Geodjango: [WinError 127] : The specified procedure could not be found

Im trying to use Django with Geodjango, I followed all documentation steps, but still got this error when trying to make migrations:
OSError: [WinError 127] : The specified procedure could not be found
The models.py is correct, I'm using from geodjango site, and this is my settings.py
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 = 'ci3qd6ti+d+#-4pae7d*)^8nmmgb2j#cacivgt8rdvsngu2$mj'
# 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',
'django.contrib.gis',
'world',
]
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 = 'geodjango.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 = 'geodjango.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'test',
'USER': 'postgres',
'PASSWORD': '*********',
'HOST': '127.0.0.1',
'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/'
And this is the error I get:
>>> python manage.py makemigrations
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute
django.setup()
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\apps\registry.py", line 112, in populate
app_config.import_models()
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\apps\config.py", line 198, in import_models
self.models_module = import_module(models_module_name)
File "C:\Users\hades\AppData\Local\Programs\Python\Python37\Lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
File "<frozen importlib._bootstrap>", line 983, in _find_and_load
File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 728, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\hades\PycharmProjects\meumapa\geodjango\world\models.py", line 3, in <module>
from django.contrib.gis.db import models
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\contrib\gis\db\models\__init__.py", line 3, in <module>
import django.contrib.gis.db.models.functions # NOQA
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\contrib\gis\db\models\functions.py", line 4, in <module>
from django.contrib.gis.db.models.fields import BaseSpatialField, GeometryField
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\contrib\gis\db\models\fields.py", line 3, in <module>
from django.contrib.gis import forms, gdal
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\contrib\gis\forms\__init__.py", line 3, in <module>
from .fields import ( # NOQA
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\contrib\gis\forms\fields.py", line 2, in <module>
from django.contrib.gis.geos import GEOSException, GEOSGeometry
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\contrib\gis\geos\__init__.py", line 5, in <module>
from .collections import ( # NOQA
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\contrib\gis\geos\collections.py", line 9, in <module>
from django.contrib.gis.geos.geometry import GEOSGeometry, LinearGeometryMixin
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\contrib\gis\geos\geometry.py", line 8, in <module>
from django.contrib.gis import gdal
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\contrib\gis\gdal\__init__.py", line 28, in <module>
from django.contrib.gis.gdal.datasource import DataSource
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\contrib\gis\gdal\datasource.py", line 39, in <module>
from django.contrib.gis.gdal.driver import Driver
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\contrib\gis\gdal\driver.py", line 5, in <module>
from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\contrib\gis\gdal\prototypes\ds.py", line 9, in <module>
from django.contrib.gis.gdal.libgdal import GDAL_VERSION, lgdal
File "C:\Users\hades\PycharmProjects\geodjango\venv\lib\site-packages\django\contrib\gis\gdal\libgdal.py", line 47, in <module>
lgdal = CDLL(lib_path)
File "C:\Users\hades\AppData\Local\Programs\Python\Python37\Lib\ctypes\__init__.py", line 356, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 127] The specified procedure could not be found
I checked and all requeriments for geodjango are installed.
Any suggestions?
You probably have multiple Python versions and there is conflict between them.
Try to install the GDAL on your virtualenv and ensure that the gdal202.dll is in your virtualenv context.
Also ensure that you installed the right compiled version from https://www.lfd.uci.edu/~gohlke/pythonlibs/#gdal, using pip and inside your virtualenv.
The GDAL DLL will be in the gdal installation path. I use a code like this in settings.py to setup GeoDjango on Windows:
try:
import gdal
gdal_path = Path(gdal.__file__)
OSGEO4W = os.path.join(gdal_path.parent, 'osgeo')
os.environ["OSGEO4W_ROOT"] = OSGEO4W
os.environ["GDAL_DATA"] = os.path.join(OSGEO4W, "data", "gdal")
os.environ["PROJ_LIB"] = os.path.join(OSGEO4W, "data", "proj")
os.environ["PATH"] = OSGEO4W + ";" + os.environ["PATH"]
GEOS_LIBRARY_PATH = str(os.path.join(OSGEO4W, "geos_c.dll"))
GDAL_LIBRARY_PATH = str(os.path.join(OSGEO4W, "gdal301.dll"))
except ImportError:
GEOS_LIBRARY_PATH = None
GDAL_LIBRARY_PATH = None
"OSError in Geodjango: [WinError 127] : The specified procedure could not be found" This error is causing due to the Mismatch version of the D-Jango and the G-dal Libraries. Kindly visit the Official Documentation of the Geo-Django to get the Details of Supported G-Dal version. Once you match and install the correct version things will work smoothly.
Note: There are some forums which says you can navigate to this Path
"Lib\site-packages\django\contrib\gis\gdal\libgdal.py"
and open the libgdal.py Python file, then add the DLL name (say gdal303.dll) into the lib_names list. This is not required though
If you are using the Correct versions the required libraries would be definitely installed and present in the respective python files.
Here is the command that you can use to check the version
all the installed packages details: pip freeze
DJnago-version: django-admin --version
Gdal version: gdalinfo --version

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.

Categories