I just started working on a project,
I am using Django1.10, I wanted to use mongoDB as backend...
I tried all possible ways, django-mongo-engine requires django-nonrel1.5,
but if I used it then I have to do lot of work, and its complicated...
I tried django-mongoengine also but it was only tested on django1.9, (django 1.9 not supporting admin)
So now I decided to use pymongo...
I need help How can I configure database? and How to work with django without ORM?
EDIT :
This is my setting.py file with django-mongoengine
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = '------------'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mongoengine',
'LocalTeamsApp'
]
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 = 'LocalTeams.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 = 'LocalTeams.wsgi.application'
# MongoDB settings
MONGODB_DATABASES = {
'default': {'name': 'django_mongoengine'}
}
DATABASES = {
"default": {
"NAME": '****',
"PASSWORD": '****',
"USER": '****',
'ENGINE':'django.db.backends.dummy'
}
}
INSTALLED_APPS += ["django_mongoengine"]
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',
},
]
AUTH_USER_MODEL = 'mongo_auth.MongoUser'
AUTHENTICATION_BACKENDS = (
'django_mongoengine.mongo_auth.backends.MongoEngineBackend',
)
SESSION_ENGINE = 'django_mongoengine.sessions'
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
Then I fired the cmnd
python manage.py runserver
I got following error:-
Unhandled exception in thread started by <function wrapper at 0x7f8648b43ed8>
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 113, in inner_run
autoreload.raise_last_exception()
File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 249, in raise_last_exception
six.reraise(*_exception)
File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper
fn(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate
app_config = AppConfig.create(entry)
File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 90, in create
module = import_module(entry)
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named django_mongoengine
If you don't want to use the ORM then you can delete or comment out DATABASE = {} in settings.py.
A solution would be to create a connector that uses pymongo. Example of mongodb_connector.py:
from pymongo import MongoClient
from bson.json_util import dumps
class MongoConnector:
username = 'user'
password = 'pass'
host = 'localhost'
port = '27017'
url = host + ':' + port
client = MongoClient(mongo_url,username=username,password=password,authSource='admin',authMechanism='SCRAM-SHA-256')
def find(self,db, collection, name):
db = client[db]
collection = db[collection]
response = collection.find_one({"name":str(name)})
return dumps(response)
Now you can get an object with:
from mongo_connector import MongoConnector
mongo = MongoConnector()
doc = mongo.find('mydb','mycollection','name')
Related
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.
My settings.py file:
"""
Django settings for myproject project.
Generated by 'django-admin startproject' using Django 2.2.13.
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 = 'af^zgg5*t&h)3dghcvd#9o1#st9b(bgh#5a32%m%!g38u(tl!f'
# 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',
'chat',
'channels',
]
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 = 'myproject.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 = 'myproject.wsgi.application'
ASGI_APPLICATION = 'asgi.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')
]
And my asgi.py:
"""
ASGI config for myproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = ProtocolTypeRouter({
'http': get_asgi_application()
})
Error:
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
June 02, 2022 - 07:12:02
Django version 3.0, using settings 'myproject.settings'
Starting ASGI/Channels version 3.0.4 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\routing.py", line 28, in get_default_application
module = importlib.import_module(path)
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\importlib\__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 978, in _gcd_import
File "<frozen importlib._bootstrap>", line 961, in _find_and_load
File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'asgi'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\management\commands\runserver.py", line 107, in inner_run
application=self.get_application(options),
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\manag
unserver.py", line 132, in get_application
return StaticFilesWrapper(get_default_application())
File "C:\Users\pc\AppData\Local\Programs\Python\Python36\lib\site-packages\channels\routi
in get_default_application
raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'asgi'
i have updated my django from 2.2 to 3.0 but the problem don't go please do something
and the asgi.py file was created by me
just want the server to recognize the routing application and start working
I've followed the channels 2 tutorial, but I'm getting this error after runningI've followed the channels 2 tutorial, but I'm getting this error after runningI've followed the channels 2 tutorial, but I'm getting this error after running
# WSGI_APPLICATION = 'myproject.wsgi.application'
ASGI_APPLICATION = 'asgi.application'
Note how the WSGI example also has the project name? I suspect you need to include projectname in the setting, eg,
ASGI_APPLICATION = 'projectname.asgi.application'
The channels docs seems to support this format (https://channels.readthedocs.io/en/stable/installation.html)
The project seemed fine till yesterday, but suddenly , when I tried to start the server after some settings changes today, this error pops up everytime:
Traceback (most recent call last):
File "/PROJECT/manage.py", line 21, in <module>
main()
File "/PROJECT/manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute
django.setup()
File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate
app_config = AppConfig.create(entry)
File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 224, in create
import_module(entry)
File "/usr/local/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 984, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'd'
the project manage.py file :
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PROJECT.settings.production')
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()
Please help me solve this and please do ask if you need more information.
Thank you in advance.
EDIT : Add settings
settings/base.py
"""Django settings for PROJECT project."""
import os
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
INTERNAL_IPS = [
'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',
'rest_framework',
'rest_framework.authtoken',
'django_filters',
'hrm',
'inventory',
'notification',
'production',
'django_celery_beat',
]
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',
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
ROOT_URLCONF = 'MIST_ERP.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 = 'MIST_ERP.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
# IN RESPECTIVE SETTINGS FILES
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
BASE_DIR / "static",
]
# STATIC_ROOT = os.path.join(BASE_DIR, "static")
# Media Settings ( Profile photos, Project photos )
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / "media"
# AUTHENTICATION BACKENDS
AUTHENTICATION_BACKENDS = [
"django.contrib.auth.backends.ModelBackend",
"rest_framework.authentication.SessionAuthentication",
"rest_framework.authentication.TokenAuthentication",
]
# REST FRAMEWORK CONFIG
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'PAGINATE_BY': 10,
}
# MEMCACHED
"""
Memcached is an entirely memory-based cache server,
The fastest, most efficient type of cache supported natively by Django,
"""
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'TIMEOUT': None,
'OPTIONS': {
'server_max_value_length': 1024 * 1024 * 2,
}
}
}
# LOGGING
LOG_PATH = BASE_DIR / 'logs'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': f'{LOG_PATH}/debug.log',
},
'file_ldap': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': f'{LOG_PATH}/debug_ldap.log',
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
"django_auth_ldap": {
"level": "DEBUG",
"handlers": ["file_ldap"],
'propagate': True,
}
},
}
# SETTINGS VARS
LOGIN_URL = '/login/'
# DJANGO AUTO FIELD
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
development.py ( currently being used )
from PROJECT.settings.base import *
import os
DEBUG = True
INSTALLED_APPS += 'debug_toolbar'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
In the deployment.py, you should wrap the 'debug_toolbar' string in a collection, for example a list, otherwise you will add one item per character to the INSTALLED_SETTINGS, and thus then you would load as apps 'd', 'e', 'b', etc.
You thus can rewrite this to:
# deployment.py
# …
INSTALLED_APPS += ['debug_toolbar']
# …
After trying to upload my django-project to heroku i get the following error, even though I tried to configure setting.py in accordance with heroku documentation. Tried to fix it myself for couple of days but I clearly got no idea about what is wrong.
-----> $ python manage.py collectstatic --noinput
Traceback (most recent call last):
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/app/.heroku/python/lib/python3.7/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.7/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 187, in handle
collected = self.collect()
File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 104, in collect
for path, storage in finder.list(self.ignore_patterns):
File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/finders.py", line 130, in list
for path in utils.get_files(storage, ignore_patterns):
File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files
directories, files = storage.listdir(location)
File "/app/.heroku/python/lib/python3.7/site-packages/django/core/files/storage.py", line 316, in listdir
for entry in os.scandir(path):
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_3daca1eccd4631486a8597ada28d44da/static'
! Error while running '$ python manage.py collectstatic --noinput'.
See traceback above for details.
You may need to update application code to resolve this error.
Or, you can disable collectstatic for this application:
$ heroku config:set DISABLE_COLLECTSTATIC=1
https://devcenter.heroku.com/articles/django-assets
! Push rejected, failed to compile Python app.
! Push failed
Here is my django 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/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '6e71nuw7=a-eow4ywhqfp6f+_7s-y7wo!4scy7xhj2vbem3#)m'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ["dyadyanurik-visitka.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',
'visitka.apps.VisitkaConfig',
'storages',
]
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 = '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/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY")
AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME")
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage"
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
Any ideas about it?
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.