Setting up Django with MongoDB

mongo-djangoIn this post, we will go through setting up MongoDB 2.6 together with Django 1.6. By default, Django doesn’t contain support for MongoDB. It isn’t difficult, however, to introduce support for the NoSQL database following the steps in this tutorial.

Assuming our Django and MongoDB is installed and a basic project is configured and running, we will add the missing steps to persist a Python object into MongoDB from our Django application. I covered installing MongoDB in this post.

Setting up Django to work with MongoDB:

  1. We will need to install mongoengine modules into Python:
    pip install mongoengine
  2. Now go to your settings.py file in your Django application and replace the current database engine with a dummy one. That will instruct Django to stop using its built-in database engines.
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.dummy'
        }
    }
  3. To enable MongoDB database engine, paste the following code anywhere in the settings.py file and change your database name, username, and password correspondingly:
    from mongoengine import connect
    connect('employeedb', username='my_username', password='secret_password')
    
  4. If you want MongoDB to also handle your session tracking, add the following code to the settings.py file:
    SESSION_ENGINE = 'mongoengine.django.sessions'
    SESSION_SERIALIZER = 'mongoengine.django.sessions.BSONSerializer'
    

    but also make sure the following is in your MIDDLEWARE_CLASSES:

    'django.contrib.sessions.middleware.SessionMiddleware'

    and the following in your INSTALLED_APPS:

    django.contrib.sessions
  5. That’s it for the MongoDB engine installation into Django. Next, we’ll test it out by saving an Employee object to MongoDB via Django.

Persisting an Object to MongoDB:

  1. In your Django application’s models.py file, create a new model called Employee. We will then persist it.
    from django.db import models
    from mongoengine import *
    
    # Create your models here.
    
    class Employee(Document):
        email = StringField(required=True)
        first_name = StringField(max_length=50)
        last_name = StringField(max_length=50)
  2. Now create a new action in the views.py file (or do the following in the Django shell instead) and enter the following code to create a new employee object and persist it into the MongoDB database.
    from django.shortcuts import render
    from models import Employee
    
    # Create your views here.
    
    def index(request):
        employee = Employee.objects.create(
            email="pedro.kong@company.com",
            first_name="Pedro",
            last_name="Kong"
        )
        employee.save()
        return render(request, 'core/index.html', {})
    
  3. Now when you go to the URL that invokes this view action,  a new employee object will be created and persisted to the MongoDB database as if any of the standard database engines connectors delivered with Django were used.
  4. Check your MongoDB database (one called employeedb in this tutorial) and you should see a table named employee with the number of records in it that equals the number of times you went to the URL triggering the index() action.
Bookmark the permalink.
  • Jno skyvonski

    Getting some feedback from your experience with django and mongodb would be really appreciated. I’m thinking about updating our database with mongodb but I need some feedback from people who have done this before. Are you using services like http://mongohq.com / http://mongolab.com ??? for your admin, have you tried http://humongous.io??? thanks in advance

  • omouse

    do you know if mongoengine works with Django 1.6 and 1.7?

    • pkout

      Hi. I know it works with Django 1.6 as I used it with it. I never tried
      it with 1.7, but I don’t see a reason why it would not work as well.

  • pkout

    Hi. I know it works with Django 1.6 as I used it with it. I never tried it with 1.7, but I don’t see a reason why it would not work as well.

  • Arvind Das

    django works with 1.7 , i am currently updated to 1.8

  • Ameesha Mittal

    I am getting this error again n again even though i configured as directed:

    raise ImproperlyConfigured(“settings.DATABASES is improperly configured. ”
    django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.

    • Do you found any fix for this? I got the same error 🙁