CSC/ECE 517 Fall 2014/ch1a 8 sn

From Expertiza_Wiki
Jump to navigation Jump to search

Django Framework

Django<ref>http://www.djangoproject.com/</ref><ref>http://www.djangobook.com/en/2.0/index.html</ref>(2005) is a high level, but heavy, open source Python<ref>http://www.python.org/</ref> web framework used to build a large scale web application. Django is named after Django Reinhardt, a gypsy jazz guitarist from the 1930s to early 1950s. A web framework is necessary to help the developers and the testers develop highly scalable and efficient web applications. Django deals with the most important problem in the domain of Web development – repetition. Even though web development is a really interesting task, there are a lot of things that require unnecessary efforts and time of the developers as well as the testers. With an MVT<ref>http://docs.djangoproject.com/en/dev/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names</ref> (Model View Template) Framework, Django is very modular and thus very much suitable for highly cohesive<ref>http://en.wikipedia.org/wiki/Cohesion_(computer_science)</ref> and low coupling<ref> http://en.wikipedia.org/wiki/Coupling_(computer_programming)</ref> tasks.

Topic Document

History

In 1998, Python CGI<ref>http://en.wikipedia.org/wiki/CGI</ref> was used to develop web applications from scratch using Python. In order to create a web application using Python CGI, we just have to create a Python script that generates output in the HTML format. We then save the script to a Web server with a “.cgi” extension and visit the page in our Web browser. Following is the sample way of creating a simple website using the script.

#!/usr/bin/env python
import MySQLdb
print "Content-Type: text/html\n"
print "<html><head><title>Food items</title></head>"
print "<body>"
print "<h1>Food items</h1>"
print "<ul>"
connection = MySQLdb.connect(user='username', passwd='password', db='food_db')
cursor = connection.cursor()
cursor.execute("SELECT food_item_name FROM food_table ORDER BY rating DESC LIMIT 10")
for row in cursor.fetchall():
	print "<li>%s</li>" % row[0]
print "</ul>"
print "</body></html>"
connection.close()

The above script generates an HTML page which will display a list of all the food items in the descending order of their rating by interacting with the corresponding table in the database.

Even though the code has several advantages such as making a website (with only one page) from the scratch, it is not difficult. The code is readable and understandable to all audiences, etc. But this approach has a lot of disadvantages. The disadvantages include repetition of code (such as database connection, authentication, etc.) for a multi-page web application. Also, if discrete entities, like databases with different configuration, are to be included in the project then we will have to rewrite and reconfigure all the pages in the web application. Thus, using CGI for web application development makes it inefficient to build and deploy.

Almost all of the problems posed by Python CGI scripting mentioned above were solved by Django. Django provided a programming infrastructure for large scale web applications, so that the developers can focus on writing clean, maintainable code without worrying about the different aspects of Project Scaffolding<ref>http://en.wikipedia.org/wiki/Scaffold_(programming)</ref>. Based on the DRY<ref>http://en.wikipedia.org/wiki/Don't_repeat_yourself</ref>(Don’t Repeat Yourself) principle, Django aims at reducing repetitive pieces of information of all kinds in software development. Django also supports pluggability of different applications into the web application that you are developing.

Also, Major websites such as Pinterest, Instagram were developed using Django.

Architecture

Most of the web frameworks- such as Ruby on Rails framework- are based on the MVC pattern. MVC, which stands for Model View Controller, is a pattern which provides loose coupling among different parts of the application. In MVC Pattern, Model deals with the direct interaction with the databases. Views deal with the representation of the data on the browser. Controller deals with the user interactions and redirecting each of the user interactions to the respective module responsible for dealing with it.


On the other hand, Django framework does not really fit into the MVC framework. As mentioned earlier, it follows the MTV framework which stands for (Model Template View) Framework. Controller corresponds to the View in Django Framework. In case of the Views in Django, it plays the role of the controller. It fetches the data and decides how the data is to be displayed.


Django's Model-View-Template Achitecture

Applications

In Django terminology, an installation of Django is considered as a “Project”.

The smallest logical subset of files/folders that is fairly independent from the rest of the project can be called as an application. These subset of files include (but are not limited to) models, views, templates, static files, URLs, etc. A single Django project can have multiple applications, each of which contains the files that define an application.

All the applications that must be included inside the main project should be explicitly mentioned in the variable INSTALLED_APPS inside the settings.py.

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'books'
)

Models

In Django, a model is defined as the single source for all the data. It defines how data is accessed, processed and validated. It also contains the structure and relationship of all the data that is used by the application. Models are used to define the structure of your database. Each model is converted into a database table and each attribute inside a model is converted into a column of that table. All this is handled by Django implicitly.

Consider the following example about an application called ‘books’ that contains:

  • Author: which has a first_name and last_name attributes
  • Book: which has title, author and publication date as its attributes

We can write models for the above application like:

class Author(models.Model):
   first_name = models.CharField(max_length=30)
   last_name = models.CharField(max_length=40)

class Book(models.Model):
   title = models.CharField(max_length=100)
   authors = models.ManyToManyField(Author)
   publication_date = models.DateField()

Once all the models for your application have been created, you can validate them by using:

python manage.py validate <app_name>

Django also dynamically generates “Create Table” statements for each of these models. These statement can be viewed using the command:

python manage.py sqlall <app_name>

The above command would give the following output:

BEGIN;
CREATE TABLE "books_author" (
    "id" serial NOT NULL PRIMARY KEY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(40) NOT NULL,
)
;
CREATE TABLE "books_book" (
    "id" serial NOT NULL PRIMARY KEY,
    "title" varchar(100) NOT NULL,
    "publication_date" date NOT NULL
)
;
CREATE TABLE "books_book_authors" (
    "id" serial NOT NULL PRIMARY KEY,
    "book_id" integer NOT NULL REFERENCES "books_book" ("id") DEFERRABLE INITIALLY DEFERRED,
    "author_id" integer NOT NULL REFERENCES "books_author" ("id") DEFERRABLE INITIALLY DEFERRED,
    UNIQUE ("book_id", "author_id")
)
;
COMMIT;

and all the tables would be created immediately as soon as you run the command stated below:

python manage.py syncdb

Views

The front-end of the web-application is equally important as the model and the controllers. The basic function of the view is to accept an HTTP request and send a response. Basically Django has two types of views – Generic Views & Class based views. Generic views just take one parameter – “request”. Following is the format of the code to display Hello World.

from django.http import HttpResponse
    	def hello_world(request)
                    	return HttpResponse(“hello world”)

Here, the method class hello_world has a parameter called “request”. This is the parameter that contains all the information of the HttpRequest. After the request has been processed, the HttpResponse object is returned back. This HttpResponse object is initialized with the string “hello world”.

Generic views mostly consist of functions. Maintaining a program with a lot of functions is difficult. This reduces the modularity of the program. In order to support classes, Class based views were introduced. Class based views consist of classes which handle all the functionality in the front end. Classes are extensible and hence reusable. We can inherit different views(classes) and include it in our class. For example, if we want to include a view which displays the contacts, we will write the following code.

from django.views.generic import ListView
from books.models import contacts
class ContactsList(ListView)
    	model = contacts

In the above program, we have imported the ListView from the generic module. As we want to display the contacts from the database, we have imported the database “contacts”. The class ContactsList inherits the ListView class and extracts all the functionality in that class. The “contacts” database is imported and assigned to the model so as to display the contacts in the form of a list view.

Just making the views is not enough. We need to map the views with the URL requests. This is done in the URLConf file – urls.py. It basically acts like a routing table to route the URL requests to the appropriate method call in the view. Suppose we want to make Django aware that the function hello_world() is actually a view function. In order to do that, we will have to write the following code:

    	from django.conf.urls.defaults import patterns, include, url
    	from hellworldproject.views import hello
    	urlpatterns = patterns(‘’. url(r’hello_world/$, hello_world)

In the above code, the “pattern” function saves the required URL pattern in the “urlpatters” attribute. So, after everything is set up, we run our web application with a url say [web-address]/hello_world/. Now, Django first goes to the settings.py file in the project directory and searches for the files which handles the URLConf part. Suppose the name of the files is urls.py. It dives into the urls.py files and linearly matches the requested url with the url patterns in the file and checks which method call is responsible for handling the request. After that, when it finds the method(here, hello_world), it passes an HttpRequest object to it. After the processing the request, it creates an HttpResponse object and then converts it into HTML code by adding the necessary formatting to the response in order for it to be displayed as a view on the screen.

Templates

In Django, templates are generally used to define how webpages of the application are supposed to look like. Template defines the structure of the webpage and also has additional elements that help access variables, run python statements and much more.

Data can be passed to templates which can be used by the templates to display to the user or perform actions on the data and create dynamic views based on the data.

Variables

We can access any data passed to the templates and use them as regular python variables. The below lines of code shows how variables can be accessed:

Author: {{author.last_name}}, {{ author.first_name }}

The above code will just print the author’s name on the webpage.

Tags

Templates also provide the ability to write python code inside them and execute them just like they would run inside a “.py” file. These elements are known as tags and look like {% tag %}

Given below is the example of a “for” loop that is defined inside a template:

{% for book in books_list %}
    <li>{{ book.title }}</li>
{% endfor %}

You can process data (though it is not logical to do so in a template), write conditional statements or just declare variables inside tags and used them later in the template file.

Filters

Filters in templates can be defined as helper functions. They are a very powerful tool that reduces the code needed for basic (or sometimes even complex) post-processing of data.

For example, the title of a book that can be added to your application could be one of ‘HARRY POTTER’, ‘HaRrY pOtTeR’ or ‘harry potter’. To standardize the format of the book title which you want to show on your website, we can simply write

{{book.title|title }}

which capitalizes the first character of each word and turn all other characters to lower.

Django also provide the ability to write custom filters and make it available to all the templates in your application. Django provides tags and filters to control internationalization in templates. They allow for granular control of translations, formatting, and time zone conversions.

Admin Site

For a certain class of Web sites, an admin interface is an essential part of the infrastructure.

This is a Web-based interface, limited to trusted site administrators, that enables the adding, editing and deletion of site content. So the admin site has to authenticate users, display and handle forms, validate input, and so on. But the best part about Django is that it does all of this and more for you – in just a few of lines of code. This is also one of the reasons why Django is called a “heavy” web development framework.

To access the Django admin interface, we just have to add /admin to your project url.


Django Admin site login page


We would also have to create a superuser, which can be done by following the steps given below.

$ python manage.py createsuperuser

Enter the admin username and email address:

Username: admin
Email address: admin@example.com

Choose the password for the admin account:

    Password: **********
    Password (again): *********
    Superuser created successfully.


Default admin site home page


Django contains a file called admin.py where you can define models for the admin site and then enable them so that they will appear on the admin site. Using the example of the Author Model described in the sections above, let us add it to the admin site:

    class AuthorAdmin(admin.ModelAdmin):
        pass

    admin.site.register(Author);

These out-of-the-box features of the Django framework is what makes it the perfect option for creating content driven websites in relatively no time at all.

Features

Django has the following features to name a few:

  • It facilitates developers with a template comprising minimal number of classes, modules, packages etc. so that the developers can focus more on the core business logic.
  • It contains an ORM (Object-Relational Mapper) that allows for the use of standard Python language. The developers need not learn any query processing language.
  • It provides with a template framework suitable for making the views.
  • It supports pluggability – that is it supports including other installed applications into your own application.
  • It has a built in administrative interface to manage the web application from an administrative level, thus providing access control.
  • It is multi-lingual
  • It supports a very useful Geographical web framework "GeoDjango"<ref>http://docs.djangoproject.com/en/1.6/ref/contrib/gis/</ref>

Disadvantages

Django is one of the most popular and widely used web framework written in the Python language. That does not mean that it does not have any disadvantages. One of the disadvantages is namely being a 'Heavy' framework as mentioned multiple times in this page. Listed below are the disadvantages of using Django for your web development needs:

  • Django is one of the oldest web development frameworks in Python with the largest community. But Django is evolving very slowly because it needs to maintain backward compatibility
  • Django has a multitude of features that work right out-of-the-box. Even though this can save a lot of time for big content websites, it is not the ideal framework for small or medium scale projects.
  • Object Relational Mapping (ORM) implemented in Django is very archaic. It is a very rigid and poorly thought implementation to say the least.
  • As defined earlier, Filters are helper functions that are accessible in Templates. They are required because Templates cannot access functions written indide Views. This may lead to developers creating redundant functions, written in Views and Templates.
  • There is no way to disable Django ORM feature. Even though many projects do not require a database, they are still compelled to configure it.

Other Frameworks

There are a lot of web development frameworks that widely used. Some of them are:

Comparison with other web frameworks

Django vs Ruby on Rails

Most of the differences lie in the way the MVC pattern is interpreted by both the frameworks.<ref>http://bernardopires.com/2014/03/rails-vs-django-an-in-depth-technical-comparison/</ref>

Models:

Everything in Ruby on Rails is based on migrations. If at any point of time, the schema of the database is changed and if it has to be reverted back to the previous schema then we can do that with the help of migrations. In case of Django, we need to depend on a third-party extension “South” (until Django 1.6) to support migrations.

Controllers:

Django considers the entire framework as the controller but Ruby on Rails has a separate entity called controllers that manage the task of interpreting the user interactions and routing to the correct method that handles the request. That is why Django is said to follow the MVT(Model View Template) framework and Ruby on Rails strictly follows MVC framework.

Views:

In Django, the amount of code that can be pushed into the views(i.e., the template) part of the application is very stringent. Only basic codes like conditional statements and simple loops are allowed. As the controller objects are not really accessible in the views, not much of the manipulation can be done in the views section of the application. This enforces a strict modularity between the models, views and templates section in the Django application making the application maintenance easier. In case of Rails, as the controller objects are accessible in the views as well, a lot of unnecessary calculations can be included in the views. This reduces modularity in the application. Thus, Django has an upper hand over Rails for this reason.

Other Features

Django has in-built features like User authentication and admin support in its web applications. This makes developing admin based web application very easy. There is no such thing in Rails.

Django vs Web2py

Web2py is inspired by Ruby on Rails. It supports Convention over Configuration just like Ruby on Rails. The administrative interface can be accessed from the browser for web2py. But, for Django, the developer has to manually configure everything.<ref>http://www.web2py.com/init/default/what</ref>

Models

Django doesn’t support migrations by itself(until 1.6). web2py supports database migrations. Also, many to many references between the tables are represented in a different way in Django and web2py. Django creates an intermediate link table whereas web2py includes the references as fields in the table.

Controllers

Web2py manages all the imports, and other things related to project scaffolding by itself. The developer just has to focus on the application development unlike Django wherein the user has to take care of all the imports in the code.

Views

If a view is undefined, then Django throws an error. But in case of web2py, it searches for mycontroller/index.html in the myapp. If that file is not present, then it creates a generic view which contains the raw response in a dictionary format on the browser.

Other features

One feature, Transactions, is supported by both Django and web2py. But the way transaction “commits” are executed is different. Django has two options “auto-commit” and “commit_on_success”. But in case of web2py, it by default commits if the transaction is success and doesn’t commit in case of failure of the transaction.

Related Materials

References

<references/>