Using Django and MongoDB to Build a Blog

You can examine the contents of the LJ_blog collection using MongoDB commands:


> use LJ_blog;
switched to db LJ_blog
> show collections;
post
system.indexes
> db.post.find();
{ "_id" : ObjectId("523d83de8491973b242e2772"), "title" : 
 ↪"First blog entry!", "text" : "This is my first 
 ↪blog entry.\r\Mihalis Tsoukalos", "text_length" : 47, 
 ↪"date_modified" : ISODate("2013-09-21T06:32:46.289Z"), 
 ↪"is_published" : true }
{ "_id" : ObjectId("523d83f88491973b242e2773"), "title" : 
 ↪"Another post", "text" : "Just another blog post!", 
 ↪"text_length" : 23, "date_modified" : 
 ↪ISODate("2013-09-21T06:33:12.321Z"), "is_published" : true }
{ "_id" : ObjectId("523d86f58491973b9e3c8c78"), "title" : 
 ↪"Just another test!", "text" : "Just another test!\r\nLJ", 
 ↪"text_length" : 22, "date_modified" : 
 ↪ISODate("2013-09-21T06:45:57.092Z"), "is_published" : true }
>

Note: every time you insert a BSON document in MongoDB, MongoDB automatically generates a new field called _id. The _id field acts as the primary key and is always 12 bytes long.

Now, you should check that everything is fine by running the test development server and trying to connect to http://localhost:8000/:


$ python manage.py runserver
Validating models...

0 errors found
September 21, 2013 - 07:25:07
Django version 1.5.1, using settings 'LJ.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

If everything is okay, you will see something similar to Figure 4 after visiting http://127.0.0.1:8000/ or http://localhost:8000/.

Figure 4. The LJblog application is up and running.

While using the application, the output from the test development server is updated and will look similar to the following:


[25/Sep/2013 12:18:28] "GET / HTTP/1.1" 200 1320
[25/Sep/2013 12:18:28] "GET /static/bootstrap/css/bootstrap.min.css 
 ↪HTTP/1.1" 200 103314
[25/Sep/2013 12:18:28] "GET /static/bootstrap/js/bootstrap.min.js 
 ↪HTTP/1.1" 200 31596
[25/Sep/2013 12:18:28] "GET /static/bootstrap/css/
↪bootstrap-responsive.css HTTP/1.1" 200 21751
[25/Sep/2013 12:18:32] "GET / HTTP/1.1" 200 1320
[25/Sep/2013 12:18:33] "GET /post/add/ HTTP/1.1" 200 1823
[25/Sep/2013 12:18:34] "GET /?all_posts HTTP/1.1" 200 1320
[25/Sep/2013 16:01:10] "GET /post/5243295f8491976bd8f016d0/edit/ 
 ↪HTTP/1.1" 200 1841
[25/Sep/2013 16:01:18] "GET /post/5243295f8491976bd8f016d0/delete/ 
 ↪HTTP/1.1" 302 0

The output is useful for debugging purposes, especially when you don't get the expected results on your Web browser.

If you want to delete the LJ_blog collection in order to start your blog from scratch, use the following command with care:


> db.post.drop()
true
> db.post.find();
> show collections;
system.indexes

Deploying the Django Web Site to a Production Server

Explaining the full deployment process is outside the scope of this article, but I want to give some useful tips. When you try to run your Django project on a production server, keep the following things in mind:

1) Turn off Debug mode inside LJ/settings.py:


DEBUG = False
TEMPLATE_DEBUG = DEBUG

2) Change the ADMINS setting inside LJ/settings.py to something useful:


ADMINS = (
    ('Mihalis', 'someEmail@Domain.GR'),
)

3) Install and activate the mod_python Apache module.

4) You can use mod_wsgi instead of mod_python.

Why Use MongoDB Instead of a Relational Database?

You may wonder why you should use a NoSQL database, such as MongoDB, instead of a traditional DBMS like MySQL or PostgreSQL. Although it would be possible to use a relational database, here are the reasons for preferring MongoDB:

  • MongoDB is generally faster.

  • MongoDB is better for high-volume traffic sites.

  • MongoDB supports sharding. Sharding (aka horizontal partitioning) is the process of separating a single database across a cluster of machines.

  • MongoDB supports replication.

  • Your data schema may change without downtime when using MongoDB.

  • Depending on the application, it may feel more natural to develop in a document-oriented database.

  • MongoDB has an easy-to-use protocol for storing large files and file metadata called GridFS.

Summary

As I've explained here, MongoDB and Django can indeed work together. However, two things are missing to be 100% Django-native: support for the Django Admin Panel and support for the syncdb command.

A link to the full code for this project is listed in the Resources section of this article.

Acknowledgement

I would like to thank Josh Ourisman for answering some questions that I had while writing this article.

Resources

Code for This Article: http://www.mtsoukalos.eu/FILES/MongoDjango.zip

MongoDB: http://www.mongodb.org

Pymongo: http://api.mongodb.org/python/current

BSON: http://bsonspec.org

Django Web Page: https://www.djangoproject.com

MongoEngine: http://mongoengine.org

Django Extensions: https://django-extensions.readthedocs.org/en/latest

The Django Book: http://www.djangobook.com/en/2.0/index.html

Twitter Bootstrap: http://en.wikipedia.org/wiki/Twitter_Bootstrap

MongoKit: http://namlook.github.io/mongokit

mod_wsgi: http://code.google.com/p/modwsgi

______________________

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState