简体   繁体   中英

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',
    ]

}

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

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',
}

}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM