Quantcast
Channel: Flamingo
Viewing all articles
Browse latest Browse all 98

Django with MongoDB

$
0
0

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:

$ pip install django==1.6.1

Install MongoDB

Download and install MongoDB using the link below:

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

Install MongoDB dependences

$ pip install https://bitbucket.org/wkornewald/django-nonrel/get/tip.tar.gz
$ pip install https://bitbucket.org/wkornewald/djangotoolbox/get/tip.tar.gz
$ pip install https://github.com/django-nonrel/mongodb-engine/tarball/master

Start project & App

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

$ django-admin.py startproject demoproject

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.

$ python manage.py startapp demoapp

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:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_mongodb_engine',
    ‘demoapp’,
)

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:

DATABASES = {
   'default' : {
      'ENGINE' : 'django_mongodb_engine',
      'NAME' : 'my_database'
   }
}

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:

class Company(models.Model):
       company_name = models.CharField( max_length=255)
       store_name = models.CharField( max_length=255, unique=True)
       address =models.CharField(max_length = 200, blank= True)
       latitude = models.DecimalField(max_digits=6, decimal_places=3)
       longitude = models.DecimalField(max_digits=6, decimal_places=3)
       class Meta:
       ordering = ['-company_name']
       def __unicode__(self):
       return self.company_name, self.store_name

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:

$ Python manage.py syncdb

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:

$ python manage.py 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.

from demoapp.models import *

Next, the following code adds our new presentation data:

def index(request):
             return render_to_response('index.html')
# Getting JSON Response
def company_List(request):
      company_List = []
    for details in Company.objects.all():
           company_List.append({'company_name': details.company_name,'store_name':details.store_name,'lat': details.latitude,'lng':details.longitude, 'address': widget.address})
         data = simplejson.dumps(company_List)
    return HttpResponse(data, mimetype='application/javascript')

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:

<!DOCTYPE html>
<html lang="en">
  <head>
    <link href='/static/css/style.css' rel='stylesheet' type='text/css'/>
    <link href='/static/css/kendo.common.min.css' rel='stylesheet' type='text/css'/>
    <link href='/static/css/kendo.default.min.css' rel='stylesheet' type='text/css'/>
  </head>
  <body>
    <div id="content">
      {% block content %}{% endblock %}
    </div>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
   <script type='text/javascript' src='/static/js/kendo.all.min.js'></script>
    {% block scripts %}{% endblock %}
  </body>
</html>

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

{% extends "layout.html" %}
{% block content %}
<h2>Demo App</h2>
<body>
<ul>
		<a href="/demoapp/map/">Stores_location</a>
</ul>
<ul>
		<a href="/demoapp/Add_store/">Add_store</a>
</ul>
</body>
<div id='widgetsGrid'>
</div>
{% endblock %}
{% block scripts %}
<script type="text/javascript">
console.log('ok');
	$(document).ready(function() {
		$('#widgetsGrid').kendoGrid({
			dataSource: {
				transport: {
					read: {
						url: '/demoapp/company_List/',
						contentType: 'application/json; charset=utf-8',
						type: 'GET',
						dataType: 'json'
					}
				}
pageSize: 10
			},
columns: [
				{
					field: 'company_name',
					title: 'Company_name'
				},
				{
					field: 'store_name',
					title: 'Store_name'
				},
				{
					field: 'lat',
					title: 'latitude',
				},
				{
					field: 'lng',
					title: 'longitude',
				},
				{
					field: 'address',
					title: 'address',
				},
			],
			height: 500,
			sortable: true,
			pageable: true
	});
	});
</script>
{% endblock %}

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:

urlpatterns = patterns(demoapp.views',
     url(r'^$', 'index'),
    url(r'^company_List/$', company_List),
)

Run the project

Start the development server:

$ python manage.py runserver

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:

class CompanyForm(forms.ModelForm):
    company_name = forms.CharField(max_length=128, help_text="Please enter the company_name.")
    store_name = forms.CharField(max_length=200, help_text="Please enter the store_name ")
    address = forms.CharField(max_length=200, help_text="Please enter the address ")
    latitude = forms.DecimalField(max_digits=12, help_text="Please enter the latitude ")
    longitude = forms.DecimalField(max_digits=12, help_text="Please enter the longitude")
    class Meta:
        model = Company
        fields = ('company_name', 'store_name', 'address', 'latitude', 'longitude')

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:

def Add_store(request):
    Context = RequestContext(request)
    if request.method == 'POST':
        form = CompanyForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return index(request)
        else:
            print form.errors
    else:
        form = CompanyForm()
return render_to_response('add_new_store.html', {'form': form}, context_instance=RequestContext(request))

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:

<html>
    <head>
        <title>Demo App</title>
    </head>
    <body>
        <h1>Add a store</h1>
        <form id="CompanyForm" method="post" action="/widgets/Add_store/">
            {% csrf_token %}
            {% for hidden in form.hidden_fields %}
                {{ hidden }}
            {% endfor %}
            {% for field in form.visible_fields %}
                {{ field.errors }}
                {{ field.help_text }}
                {{ field }}
            {% endfor %}
            <input type="submit" name="submit" value="Create New Store " />
        </form>
    </body>
</html>

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:

urlpatterns = patterns('widgets.views',
    url(r'^$', 'index'),
   url(r'^company_List/$', company_List),
    url(r'^Add_store/$', 'Add_store')
)

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:

def map(request):
    return render_to_response(map.html')

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:

<html>
<head>
<title>Demo app for Google Maps Marker using External JSON</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src = "http://maps.google.com/maps/api/js">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(12, 80),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  $.getJSON('/demoapp/companyList/', function(data) {
  //console.log(data);
            $.each( data, function(i, value) {
            //console.log(value);
    var myLatlng = new google.maps.LatLng(value.lat, value.lng);
    //alert(myLatlng);
   // console.log(myLatlng);
    var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    title: "text "+value.lon
                });
    });
});
}
</script>
</head>
<body onload="initialize()">
<form id="form1" runat="server">
<div id="map_canvas" style="width: 950px; height: 650px"></div>
</form>
</body>
</html>

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:

urlpatterns = patterns(demoapp.views',
    url(r'^$', 'index'),
    url(r'^company_List/$', company_List),
    url(r'^map/$', 'map'),
    url(r'^Add_store/$', 'Add_store')
)

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


Viewing all articles
Browse latest Browse all 98

Trending Articles