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)
Related
I want to implement login app. all the users information are in table named 'admin_users'. I am using mysql server by xampp.
when i am authenticating using user = authenticate(username=username,password=password)
On printing user I am getting None.
I am beginner in django and I could not find out whats wrong.
If I am doing AdminUsers.objects.all() I can print all the table information.
models.py
class AdminUsers(models.Model):
username=models.CharField(max_length=50)
firstname=models.CharField(max_length=50)
department=models.CharField(max_length=50)
mail=models.CharField(max_length=50)
id=models.IntegerField(primary_key=True)
password=models.CharField(max_length=200)
class Meta:
db_table="admin_users"
view.py
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username,password=password)
print(user)
return render(request,'AdminUsers/login.html')
my index.html contains simple forms with username and password.
settings.py
"""
Django settings for python_test project.
Generated by 'django-admin startproject' using Django 3.2.6.
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
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/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-j*uh&s1$j-'
# 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',
'myapp'
]
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 = 'python_test.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates'),
os.path.join(BASE_DIR,'app_kanri/templates/app_kanri/')
],
'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 = 'python_test.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydb',
'USER': 'root',
'PASSWORD': '',
'HOST': 'localhost',
'PORT': '3306',
}
}
# 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_URL = '/static/'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
Not sure what your goal is with the AdminUsers model. The default django user model has flags like is_staff and is_superuser that you can use to seperate users and their permissions with regards to what they can access on the app.
Check out the docs on the user model here
You need to insert this in your settings: AUTH_USER_MODEL = 'AppName.AdminUsers' (replace AppName with the name of the app containing AdminUsers).
Your custom User model should inherit from AbstractUser to be compatible with the authentication system (right now it will not work):
class AdminUsers(AbstractUser):
department=models.CharField(max_length=50)
class Meta:
db_table='admin_users'
Now AdminUsers will inherit fields of AbstractUser (username, email, password, is_staff, ...), read this for details.
If you have already done migrations, you need to delete migrations of the default User model.
Note also that you should name the model 'AdminUser' and not 'AdminUsers'.
I am trying to create message app with a database model using Django framework using pycharm with apache-cassandra as a database. When I try to run
python manage.py migrate
in the terminal I get the following error,
TypeError: Unknown option(s) for sync_cassandra command: app_label, check_unapplied, fake, fake_initial, interactive, migration_name, plan, run_syncdb. Valid options are: database, force_color, help, no_color, pythonpath, settings, skip_checks, stderr, stdout, traceback, verbosity, version.
My setting.py
"""
Django settings for DjangoProject project.
Generated by 'django-admin startproject' using Django 3.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
import os
from pathlib import Path
from cassandra import ConsistencyLevel
# Build paths inside the project like this: BASE_DIR / 'subdir'.
from cassandra.cqlengine.connection import session
BASE_DIR = Path(__file__).resolve(strict=True).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 = 's6+mmj8j^9qe+jy&=#^2i!cao!fnxeicaa24c^#se8n#o88t&r'
# 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',
'posts.apps.PostsConfig',
]
INSTALLED_APPS = ['django_cassandra_engine'] + INSTALLED_APPS
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 = 'DjangoProject.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 = 'DjangoProject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'sqlite': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
},
'default': {
'ENGINE': 'django_cassandra_engine',
'NAME': 'my_keyspace',
'TEST_NAME': 'MasterTable',
'HOST': '127.0.0.1',
'OPTIONS': {
'replication': {
'strategy_class': 'SimpleStrategy',
'replication_factor': 1
},
'connection': {
'consistency': ConsistencyLevel.SERIAL,
'retry_connect': True
# + All connection options for cassandra.cluster.Cluster()
},
'session': {
'default_timeout': 10,
'default_fetch_size': 10000
# + All options for cassandra.cluster.Session()
}
}
}
}
# 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/'
However when I do a migration using the sqlite3, I don't have any errors.
Probably you've already figured it out.
The answer is that Cassandra does not have to migrate, but sync_cassandra.
Try:
python manage.py sync_cassandra
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;
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.
According to the django tutorial on its official website, django creates database schema according to the model defined in the models.py. But the default engine for database is sqlite3. And it is working.
now when I installed the mysql and Mysql Connector for django and I tried to create a database I encountered with the following error:
mysql.connector.errors.ProgrammingError: 1049 (42000): Unknown database 'db.mysql.userdb'
I searched the error and found some solutions to this problem but all of them mentioned that I have to create the database myself using MYSQL Shell. But this is not what I want! According to the django website, I have to just define my model and django creates the schema of database! How can I do that?
Thanks in advance.
The following is my sttings.py file:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
SECRET_KEY = '94sf3cp(#a^)9!^zrr^zr3dfdk0nz$*4=m#v19*v)j&q^o$#ym'
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'website_user',
)
MIDDLEWARE_CLASSES = (
'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 = 'Final_DBMI.urls'
WSGI_APPLICATION = 'Final_DBMI.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'mysql.connector.django',
'NAME': 'db.mysql.userdb',
'USER': 'hadi',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306'
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/statics/'
Update
I'm using this doc and according to that there is two ways to connect to mysql:
MYSQLdb
MySQL Connector/Python
and I'm using the second one. According to the MYSQL website it should be added to settings.py in the following way:
DATABASES = {
'default': {
'NAME': 'user_data',
'ENGINE': 'mysql.connector.django',
'USER': 'mysql_user',
'PASSWORD': 'priv4te',
'OPTIONS': {
'autocommit': True,
},
}
}
Django creates the tables. It does not create the database that the tables live in; you must do that.
db settings like this,
install the mysql-python in your environment using pip
pip install mysql-python
create the database(userdb) in your mysql using below command,
create database userdb;
then your settings.py file follow these settings,
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'userdb',
'USER': 'mysql username',
'PASSWORD': 'mysql password',
'HOST': '127.0.0.1',
'PORT': '3306'
}
}
Here is reference link https://docs.djangoproject.com/en/dev/ref/settings/#databases