Django with MongoDB

Django with MongoDB

Introduction

Django is a high-level python web framework that eases building better web apps more quickly and with less code.

Django MongoDB Engine is a MongoDB backend for Django, the Python Web framework for perfectionists with deadlines.

Features

  • It consists of an object-relational mapper which mediates between data models (defined as Python classes) and a relational database (“Model”) – a system for processing requests with a web template system (“View”) and a regular-expression-based URL dispatcher (“Controller”).
  • Serialization system which can produce and read XML and/or JSON representations of Django model instances. A system for extending the capabilities of the template engine.
  • Django can be run in conjunction with Apache, NGINX using WSGI using flup (a Python module). Django also includes the ability to launch a FastCGI server and it is also possible to use other WSGI-compliant web servers.

Use case

  • Install Django
  • Install MongoDB
  • Install MongoDB dependencies
  • Start project & app
  • Add our app into project
  • Configure database
  • Create model
  • Create forms
  • Create views & URL
  • Add data with shell
  • Create Templates
  • Run Project

Solution

Install Django

Run the following command to install Django:

Install MongoDB

Download and install MongoDB using the link below:

http://docs.mongodb.org/manual/installation/#tutorials-installation

Install MongoDB dependences

Start project & App

Once the MongoDB setup is done and MongoDB server is started, we can start a Django project with the command below:

The following structure is created showing a typical Django project layout:

typical_Django_project_layout

Define the following command in project directory. This will create our first app.

This structure will be created showing a typical Django application layout:

typical_Django_application_layout

Django creates the following files for you:

  • demoapp/__init__.py: an empty, but special python file.
  • models.py: data managed with data.
  • views.py: where you’ll define all of the view functions.
  • tests.py: Like bacon, testing is good for you, but we’ll leave that for another day.

Add our app into project

We need to add your app name into the project. Go into settings.py file and add your app name:

Configure database

The database is the foundation of most web apps and the Django app is no exception. In this blog, we are going to configure the database settings and then use a Django management command to sync the database to the models.

Change the DATABASES dictionary with the following code:

Create models

Models are used to generate database tables and they have a rather nifty object relational mapping (ORM) API for getting things in and out of the database. We add the following code into models.py file:

We’ve also given our model class a couple of methods. The first one __Unicode__ is used; this method returns a Unicode object. The second one is inner Meta class on the models. This is where you’re telling the model class how it should be ordered. In this case, company object is ordered by the company_name.

Now, you can create your database with the following command:

Note: The Views & URL files can be modified as required for usage at relevant instances in the application.

Add data with shell

The manage .py provides a shell interface for the application that you can use to insert data into the Company. Begin by issuing the following command to load the Python shell:

Create the first post using the following sequence of operations:

add_data_with_shell

Create Views, URL & Templates

We first need to import the demoaapp model objects and create presentation of the data. This means we must add the following import statement at the top of the file.

Next, the following code adds our new presentation data:

To accomplish this, we created an empty array and then looped through all the details, and for each details, we appended the desired JSON to the array. Finally, we used the simple json.dumps function to convert the array to JSON. Finally, the above presentation data code includes index page and how to get the json response into database.

To create index page

In the templates folder, we added the following two HTML files. The layout.html file is a base template and index.html derives from layout.html.

In the base template, we defined the html that will be used for all templates in the demoapp package. We define the links UI style sheets and the references to the jQuery js files:

In the index.html template, we extend the layout.html template and add following codes:

The HTML code example demonstrates how we utilize the data passed to the template via its context. We make use of the company_name, store_name, lat&lng variable and our Company objects.   If a page is undefined or contains no elements, we display a message stating there are no pages present. Otherwise, the pages within the Company objects are presented in a HTML list.

To Create URL

Before we could run the applications, we need to create demoapp URL to display the index.html page.

We add the following code:

Run the project

Start the development server:

Visit the URL, http://127.0.0.1:8000/demoapp/.  You should now be able to see the screenshot below.

run_the_project

Create a form

First, create a froms.py file in demoapp directory and import the demoapp model objects. As we already have one model defined for demoapp (Company), we will create ModelForms.

Add the following code:

To create an Add New Store on views.py

With our ComapnyForm class now defined, we are now ready to create a new view to display the form and handle the posting of form data.

To do this, add the following code:

First, we check the HTTP request method, to determine if it is a HTTP GET or POST. Now, we can use the POST method for this process and validate the form. Finally we save the form.

To create add New Store Template

We create an add_new_store.html file on template directory and add the following code:

To create a view for Add New Store

We need to create demoapp URL to display the add_new_store.html page.

We add the following code:

To display the Json object into Google Maps

Create views for map function:

We are ready to create a views function to display the json object into Google map using Company objects (store latitude & longitude values).

Add following code into views.py file:

To create a Google Map Template

First, we create a map.html file on template directory. In this template, we have used “show” to store exact location using Json object.

Add the following code:

Now, the above code gets the json object and puts the object such as (Latitudes & longitudes) into Google Maps Marker.

To create URL for Map function

Add the following code to show the map.html page:

Visit the URL, http://127.0.0.1:8000/demoapp/map/ . You should now be able to see the screenshot below:

map_function

Conclusion

  • In this blog, we have discussed Django framework with MongoDB process.
  • We have shown how to create JSON object into Google maps.
  • We have discussed about the features.

References

13168 Views 9 Views Today
  • Udayan Saha

    I am building my first Python web app using Python 2.7.10, MongoDB 3.0, Django 1.5 and Django-nonrel. Please let me know web server suitable for production deployment of my web application using above mentioned combination.

    • Udayan Saha

      I gave a try with Apache/mod_wsgi but it seems technically there is no combination available for correctly running mod_wsgi with VC9 version of Python 2.7. What is alternative solution?

  • nakul

    If i dont want MODEL layer….directly i want to run query then how can i

  • siddarth sen

    The part on using JSON objects for GMaps was really useful! A great article on how to use MongoDB and Django. I have found another framework for connecting Django and MongoDB: djongo? https://github.com/nesdis/d…. Appears to be even more easier to use. Has anyone used this before?