Django ignores test database settings - python

I have an app deployed on pythonanywhere which runs fine. Problem is that when I want to run test django, my test database settings is completely ignored.
Each time I run test I get the following message.though.
Creating test database for alias 'default'...
Got an error creating the test database: (1044, "Access denied for user 'funnshopp'#'%' to database 'test_funnshopp$funn'")
Database name for the app is funnshopp$funn. It can be seen that django somehow always tries to create the test database by appending test_ to the database name. Never minding what I have in DATABASES settings
Below is my full settings file ( Test runs fine on my PC and I am using Django 2.0, though I started the project with Django 1.11)
"""
Django settings for funnshopp project.
Generated by 'django-admin startproject' using Django 1.11.7.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
from django.urls import reverse_lazy
from django.core.exceptions import ImproperlyConfigured
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def get_env_variable(var_name):
"""Get the environment variable or return exception"""
try:
return os.environ[var_name]
except KeyError:
error_msg = "Set the {} environment variable".format(var_name)
raise ImproperlyConfigured(error_msg)
ENV_ROLE = get_env_variable("ENV_ROLE")
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = get_env_variable("SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
FUNN_PASS = False
if ENV_ROLE == "development":
DEBUG = True
FUNN_PASS = get_env_variable('FUNN_PASS')
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'asset',
'debit',
'communication',
'establishment',
'credit',
'personnel',
'relation',
'debug_toolbar',
'captcha',
'guardian',
'rules',
'coverage',
'django_extensions',
'pure_pagination',
'sorl.thumbnail',
'django_addanother',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'guardian.backends.ObjectPermissionBackend',
'rules.permissions.ObjectPermissionBackend',
)
MIDDLEWARE = [
'debug_toolbar.middleware.DebugToolbarMiddleware',
'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 = 'funnshopp.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 = 'funnshopp.wsgi.application'
INTERNAL_IPS = ('127.0.0.1', 'localhost')
DEBUG_TOOLBAR_PANELS = [
'debug_toolbar.panels.versions.VersionsPanel',
'debug_toolbar.panels.timer.TimerPanel',
'debug_toolbar.panels.settings.SettingsPanel',
'debug_toolbar.panels.headers.HeadersPanel',
'debug_toolbar.panels.request.RequestPanel',
'debug_toolbar.panels.sql.SQLPanel',
'debug_toolbar.panels.staticfiles.StaticFilesPanel',
'debug_toolbar.panels.templates.TemplatesPanel',
'debug_toolbar.panels.cache.CachePanel',
'debug_toolbar.panels.signals.SignalsPanel',
'debug_toolbar.panels.logging.LoggingPanel',
'debug_toolbar.panels.redirects.RedirectsPanel',
]
GOOGLE_RECAPTCHA_SITE_KEY = get_env_variable("GOOGLE_RECAPTCHA_SITE_KEY")
GOOGLE_RECAPTCHA_SECRET_KEY = get_env_variable("GOOGLE_RECAPTCHA_SECRET_KEY")
LOGIN_REDIRECT_URL = reverse_lazy('personnel:dashboard')
LOGIN_URL = reverse_lazy('personnel:login')
LOGOUT_URL = reverse_lazy('personnel:logout')
if ENV_ROLE == "development":
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
else:
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '***#gmail.com'
EMAIL_HOST_PASSWORD = '*******'
DEFAULT_FROM_EMAIL = '***#gmail.com'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DEPLOYMENT_PLATFORM = get_env_variable("DEPLOYMENT_PLATFORM")
if DEPLOYMENT_PLATFORM == "heroku-plus-local":
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'funn',
'USER': 'postgres',
'PASSWORD': get_env_variable('FUNN_PASS'),
'HOST': 'localhost',
'PORT': 5432
}
}
else: # DEPLOYMENT_PLATFORM == "pythonanywhere"
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'USER': 'funnshopp',
'NAME': 'funnshopp$funn',
'PASSWORD': get_env_variable('FUNN_PASS'),
'HOST': 'funnshopp.mysql.pythonanywhere-services.com',
'TEST':{
'ENGINE': 'django.db.backends.sqlite3', # for sqlite3
'NAME':'test.db',
# 'ENGINE': 'django.db.backends.mysql',
# 'NAME':'funnshopp$test_default'
},
},
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Africa/Lagos'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
AUTH_USER_MODEL = 'personnel.Person'
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
import django_heroku
django_heroku.settings(locals())
Below is the result of pip freeze
alabaster==0.7.10
Babel==2.5.1
beautifulsoup4==4.6.0
certifi==2017.11.5
chardet==3.0.4
colorama==0.3.9
coverage==4.4.2
dj-database-url==0.4.2
dj-static==0.0.6
Django==2.0.1
django-addanother==2.0.0
django-archive==0.1.5
django-braces==1.12.0
django-debug-toolbar==1.9.1
django-extensions==1.9.9
django-guardian==1.4.9
django-heroku==0.2.0
django-pure-pagination==0.3.0
django-recaptcha==1.3.1
django-toolbelt==0.0.1
django-webtest==1.9.2
docutils==0.14
funcsigs==1.0.2
gunicorn==19.7.1
idna==2.6

This is a common and correct behavior. Django when testing will always try to create new database, and you should never try to test you application on your live/production database.
Your tests should be constructed in a way, where you create your objects and then test their behavior. You are using postgres, on heroku and mysql on development server. If you want to use this databases to test you app, you have to add django user to you postgres/mysql with rights to create and delete databases/tables.
You can also avoid this by adding this setting to your settings.py (this is what I like to do when I do not use any other extensions and sqlite3 database is just enough. I run my tests by typing python manage.py test
if any([arg in sys.argv for arg in ['jenkins', 'test']]):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'mydatabase',
}
}

I think you should change how you format your settings.py, you must not put if conditions inside it but use different settings based on the environment you are working on!
I recommend you to read this tutorial.
When you have the proper layout you can change the database in the different settings file ;)!

I solved the problem by reorganizing my settings file according to the pattern suggested here Recommended Django Project Layout.
Now my test runs fine on pythonanywhere.
Btw, I created a gist here which deals with the problems of virtual environments and layouts and how to handle virtual environment variables.

As you know, when you are running tests, Django isolates the changes made to the database. That is why it tries to create a database which is denied by the DB engine. You can either:
Create a database, grant access to the user and use --keepdb to run the tests
Or grant access to the DB user to create a database. Something like:
ALTER USER username CREATEDB;

Related

My registered accounts in herokuapp is not shown in django admin [duplicate]

This question already has answers here:
Heroku app database resetting
(1 answer)
Heroku and Django, database resets when heroku restarts the site
(1 answer)
SQLite database hosted on Heroku getting automatically reset
(1 answer)
Can I use a file based database on Heroku?
(1 answer)
Closed last year.
I have created a django app and deployed it in Heroku.
The web app works fine and the user registration and login works too.
But when I open the django admin site it doesn't show the latest registered account. I have asked a few people to test my system so surely, there will be a few new accounts but the only accounts there were the ones I tested with a dummy account before deploying in heroku.
This is my admin.py
from django.contrib import admin
# Register your models here.
settings.py
"""
Django settings for sentiment_emotion_analysis project.
Generated by 'django-admin startproject' using Django 2.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sentiment.settings")
# import django
# django.setup()
# from django.core.management import call_command
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
messages.DEBUG: 'alert-debug',
messages.INFO: 'alert-info',
messages.SUCCESS: 'success',
messages.WARNING: 'alert-warning',
messages.ERROR: 'danger',
}
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'g&x!0fjh8c8)e_-z#gs1^lbngvqwk2(o3s(5zg!o&woxdsu_un'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['sentymeter.herokuapp.com', '127.0.0.1']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'sentiment',
'user',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'sentiment_emotion_analysis.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'sentiment_emotion_analysis.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
MODELS = os.path.join(BASE_DIR, 'sentiment/models')
How to I solve this issue?

Why getting settings.DATABASES is improperly configured. Please supply the ENGINE value.?

I have not written so much line just created a new database in setting.py and routers file in django project.
After this run following command in shell and every this goes well and a new file with name auth_db.db.sqlite3 create.
python manage.py migrate --database=auth_db
and
C:\Users\Admin\Desktop\project\assignment>python manage.py createsuperuser --database=auth_db
Username (leave blank to use 'admin'): admin
Email address: admin#gmail.com
Password:
Password (again):
The password is too similar to the username.
This password is too short. It must contain at least 8 characters.
This password is too common.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.
setting.py:-
"""
Django settings for assignment project.
Generated by 'django-admin startproject' using Django 3.2.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
# 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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-pg_xyl$21ofn1f5n*%vaymeniyubo3h^a2jmy&b$=83!gs+ni%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'assignment.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 = 'assignment.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {},
'auth_db': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'auth_db.db.sqlite3',
},
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.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/3.2/howto/static-files/
STATIC_URL = '/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
DATABASE_ROUTERS = ['routers.db_routers.AuthRouter']
But when i tried to login in admin panel after running command python manage.py runserver i get error:
settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.

Django admin site is not showing default permissions of models

My Django admin site does not show any default permissions of any models. Actually, I checked the database and I can't find any model permission in the auth_permissions table.
I've already run python manage.py makemigrations and python manage.py migrate. I also tried deleting the database and migration files and run two above command again but doesn't work. I've already registered my models in admin.py.
Any other solutions I can try ?
admin.py
from django.contrib import admin
from .Models import *
# Register your models here.
admin.site.register(LeaveRequest)
admin.site.register(Worker)
admin.site.register(TimeSheet)
settings.py
"""
Django settings for WorkTime project.
Generated by 'django-admin startproject' using Django 3.1.3.
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 rest_framework
import dj_database_url
# 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 = '0yz04(%a^xuilqa8*#e^e)bj+n%&+jou=tg$%lb&#ox!lk1!x5'
SECRET_KEY = os.environ.get(
'SECRET_KEY', '0yz04(%a^xuilqa8*#e^e)bj+n%&+jou=tg$%lb&#ox!lk1!x5')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.environ.get('DEBUG', '') != 'False'
ALLOWED_HOSTS = ['worktime-management.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',
'rest_framework',
'api',
'rest_framework.authtoken',
'crispy_forms',
'web',
]
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 = 'WorkTime.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 = 'WorkTime.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# 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_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATIC_DIR = os.path.join(BASE_DIR,'static')
STATICFILES_DIRS = [
STATIC_DIR,
]
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Heroku: Update database configuration from $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Media root
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
# Email config
EMAIL_USE_TLS = True
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_PASSWORD = os.environ.get('MAIL_PASSWORD')
EMAIL_HOST_USER = os.environ.get('MAIL_USERNAME')
EMAIL_PORT = 587
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
# CSRF enable
CSRF_COOKIE_SECURE = True
# Rest Auth
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
]
}
# Boostrap4
CRISPY_TEMPLATE_PACK = 'bootstrap4'
AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.AllowAllUsersModelBackend', )
In your admin.py you are importing all of your models as from .Model import *. Python is a case-sensitive programming language if you have not manipulated your models.py file as Models.py.
I suppose from .models import * will do the trick
The above solution solves the problem. However, my Models is actually a folder, I've been trying to divide the models into different files which are stored in that folder. So for those who have the same idea, just simply change the folder's name into models and you're good to go :v

Connect Mongodb with Django

I am trying to connect mongodb with django, but i am getting this error
ImproperlyConfigured: 'djongo' isn't an available database backend.
Try using 'django.db.backends.XXX', where XXX is one of:
'mysql', 'oracle', 'postgresql_psycopg2', 'sqlite3'
I have read posts but they are all old and not helping me. I have created mongodb database using studio 3T, name of database is NewDataBase user is gsc-30310 port is 27017 host is localhost
Versions I am using are:
python3
Django==2.1.1
mongoengine==0.15.3
pymongo==3.7.1
Here is my settings.py file, please tell me how to setup for new version of django and python 3. thanks
"""
Django settings for RestUserAPI project.
Generated by 'django-admin startproject' using Django 2.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
import mongoengine
# 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 = '3==2yxbjdvt+hkqm#*%s7cs4g(_+cus9pdup%bxd*uk03g^&w%'
# 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',
#RestFrameWork
'rest_framework',
]
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 = 'RestUserAPI.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 = 'RestUserAPI.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
#'ENGINE': 'django.db.backends.sqlite3',
#'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
'ENGINE' : '',
'NAME' : 'local',
'USER' : 'gsc-30310',
'PASSWORD': 'gsc-30310',
'HOST': 'localhost',
'PORT': '27017',
}
}
# _MONGODB_USER = 'gsc-30310'
# _MONGODB_PASSWD = 'gsc-30310'
# _MONGODB_HOST = '127.0.0.1'
# _MONGODB_NAME = 'NewDataBase'
# _MONGODB_DATABASE_HOST = \
# 'mongodb://%s:%s#%s/%s' \
# % (_MONGODB_USER, _MONGODB_PASSWD, _MONGODB_HOST, _MONGODB_NAME)
#
# mongoengine.connect(_MONGODB_NAME, host=_MONGODB_DATABASE_HOST)
AUTHENTICATION_BACKENDS = (
'mongoengine.django.auth.MongoEngineBackend',
)
# 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/'
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
),
# 'DEFAULT_PARSER_CLASSES': (
# 'rest_framework.parsers.JSONParser',
# )
'DEFAULT_AUTHENTICATION_CLASSES':[
'rest_framework.authentication.SessionAuthentication',
#'rest_framework.authentication.BasicAuthentication'
],
'DEFAULT_PERMISSION_CLASSES':[
'rest_framework.permissions.AllowAny',
]
}
first thank you for your answers and support in this question.
I agree with Sanchit and shreesh katti answers, we can use mongoclient and mongoengine to connect with MongoDB, both works good.
I have found one another way, there is an open source project djongo and I am using djongo to connect with MongoDB database. The main benefit of djongo is that it lets you use everything that django provides ( eg models.Model).
here is link of djongo GitHub page https://github.com/nesdis/djongo
this is settings that we need to use djongo
settings.py
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'MyDB',
}
}
Django works well with Relational databases like PostGreSQL, MySQL. Every django settings needs to have a Database configuration defined with 'default' configurations it also needs database respective engine like psycopg2 for PostGreSQL, mysqlclient for MySQL - if you have multiple database configurations then you need to use database router check here for reference. In case of MongoDB - its a NoSql database which Django officially doesn't support if you really need to use MongoDB create a mongoengine configuration in views and you can define mongo credentials in settings.py
Using pymongo in django views:
client = pymongo.MongoClient(MONGO_URI)
mongodb = client[MONGO_DB_NAME]
...
class MongoClassView(View):
def post(request):
...
mapped_data = {'name': 'John'}
mongodb.get_collection('mycollection').insert(mapped_data)
return JsonResponse({})
hope this helps
You can try these steps to connect your django 2.0 or more with MongoDB database:
1) Install mongoengine for django 2.0
pip install -e git+https://github.com/MongoEngine/django-mongoengine.git#egg=django-mongoengine
2)Add these in your settings file:
from mongoengine import *
'django_mongoengine', // Add this line to installed app
MONGODB_DATABASES = {
"default": {
"name": '<db_name>',
"host": 'localhost',
"password": '',
"username": '',
"tz_aware": True, # if you using timezones in django (USE_TZ = True)
},
}
You can find the details for querying the database here
Use mongoengine and djongo to connect.
Make the following changes in your settings.py file
mongoengine.connect(
db=config.main_db,
host=config.host,
#username=config.username_admin,
#password=config.password_admin,
#authentication_source=config.authSource_admin,
#authentication_mechanism=config.authenticationMechanisms)
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': config.main_db,
# 'USER': config.username_admin,
# 'PASSWORD': config.password_admin,
# 'HOST': config.host,
# 'PORT': config.port,
}
}
use djongo to connect to your mongodb:
use these versions on your venv (if you want to use virtual env):
dataclasses==0.1
Django==2.0
djongo==1.2.30
pymongo==3.2
pytz==2018.5
sqlparse==0.2.3
and follow this: Connect MongoDB to Django (using djongo)

Error migrating MySQL database into Django. Unexpected host name

I am trying to migrate a MySQL db into Django. I created a simple database when I followed a tutorial, but now I am trying to migrate my actual db into the project. I modified settings.py to look like this (changed the databases section):
"""
Django settings for tutorial project.
Generated by 'django-admin startproject' using Django 1.11.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '********'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'helloservice.apps.HelloServiceConfig',
]
REST_FRAMEWORK = {
'PAGE_SIZE': 10
}
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': [],
'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/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'pulse',
'USER':'root',
'PASSWORD':'zzzz',
'HOST':'yyyy-backend.cluster-cwtxulgbsb88.us-east-1.rds.amazonaws.com',
'PORT':'3306',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
My error:
mysql_exceptions.OperationalError: (2005, "Unknown MySQL server host 'mysql://dev-backend.cluster-xxx.us-east-1.rds.amazonaws.com:3306' (74)")
Where the heck is it getting dev-backend.cluster as the database from?
My migrate command:
python manage.py makemigrations
python manage.py migrate
Check for settings downstream of that DATABASES assignment. A common pattern in Django projects is a layout like this:
# In settings.py, declare all the base values
DATABASES = { ... }
INSTALLED_APPS = [ ... ]
# Import other settings based on environment
if os.environ.get("environ") != "production":
from .devel import *
For better or worse this pattern or variations thereof are commonplace. You likely have an import under a conditional later in the file.
I also encountered the same problem.
if yyyy-backend.cluster-cwtxulgbsb88.us-east-1.rds.amazonaws.com is
correct?? can name resolve?
You might want to use its
IP address for connecting instead.
Because Usually the case when name resolving doesn't work on the host.

Categories