PETR KOUT - ENGINEERING AND PHYSICS

MY PERSONAL SITE AND BLOG ABOUT SOFTWARE AND HARDWARE ENGINEERING, AND PHYSICS

Setting Up Django with MongoDB

By Petr Kout, May 06, 2014


Setting Up Django with MongoDB

In 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

  • We will need to install mongoengine modules into Python:

    pip install mongoengine
  • 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'
        }
    }
  • 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')
  • 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
  • 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

  • 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)
  • 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', {})
  • 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.
  • 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.