Advertisement

A Python-3.5 Web Application with Django framework

Python is an open-source multi-paradigm programming language released in 1991 that supports Object-oriented, Structural etc paradigms and in Version-3 has some functional constructs also. Of-late it is consistently found in the top5 list in the TIOBE index. In PYPL index  it comes next only to Java in popularity  and in the last five years it is the language that grew most(8.9%) mostly at the expense of  PHP(-5%) .In the years 2007 and 2010 it was declared “language of the year”. Python is widely used in scientific circles because of the large number of libraries that provide a complete set of tools for analysis and data manipulation. Compared to other programming languages generally used for data analysis, such as R and Matlab, Python not only provides a platform for the processing of data but also has some features that make it unique. The development of an ever-increasing number of support libraries, the implementation of algorithms of more innovative methodologies, and the ability to interface with other programming languages (C and Fortran) make Python unique among its kind. Fabio Nelli the author of the book “Python Data Analytics” opines that “.. Python is not only specialized for the data analysis, but also has many other applications, such as generic programming, scripting, interfacing to databases, and more recently web development as well, thanks to web frameworks like Django. So it is possible to develop data analysis projects that are totally compatible with the Web Server with the possibility to integrate it on the Web. So, for those who want to perform data analysis, Python, with all its packages, can be considered the best choice for the foreseeable future.”With the support it gets from Google, Python will continue to grow and we will see more of that later and now we will focus on the use of Django for creating web applications including a database-based web application for which it was tailor-made.

Django

It is opined that Python has more number of web frameworks than the number of key words in it. Django, which is considered by some as Python’s answer to Rails, is a full-stack framework that comes with support for creation of artefacts for every layer of a web application. Others like Pyramid or Flask are “minimalist” -they only provide you the essential functionalities. If you need anything else, you must add those capabilities yourself, through extensions available outside the framework. For example, Flask provides powerful tools for common web development tasks, such as routing URLs to code, processing request data, and rendering templates and encourages you to bring-your-own-library for everything else. This allows programmers the flexibility to pick and choose the best components for their application. For example there is no integrated model layer and you are free to choose your data access/ORM library.   This approach gives you a lot of flexibility, and a better support for testing and no design is imposed; but your responsibilities are more. More of it later when we see “Flask” a minimal micro-framework; now we will look at Django,  the full-fledged all-in-one and high coupling framework. Django with bundled functionalities in terms of database integration, a forms library, administration interface, or migration tools may be an over-kill for small applications that don’t make use of those functionalities. However to understand the basics we will start with a small “first” app and later on see how to create a database-based web application that makes use of the above functionalities.

Installation and creation of project environment

We can install Python 3.5( Python 3.5 is preferable, as  Django for Python-3.6 seems to have some troubles) through windows installer and this installation will take care of adding the installation folder and the “Scripts” folder to the “path” environment variable. As this version of Python comes with “pip”, the Package manager for Python, we can easily install Django .In the command prompt/terminal you can change to C:\Python35( your Python  installation folder) and   execute

pip install django

For the above command to work, the “path” environment variable should contain  /Python/Scripts, the directory which contains “pip.exe” .You can check the Django installation by executing the following command.

python -m django –version

In the /Python/Scripts folder you can see the file “django-admin.py” and dango-admin is the command-line utility in Django for various administrative tasks. Django expects us to use this tool and create a project- an environment/website - to build and run our web application(s). In the command prompt/terminal change to the directory in which you want the project to be created and execute

django-admin createproject firstproject(firstproject is the project name and you can give whatever name you want).If the project is successfully created the terminal will silently return the prompt.

 In the generated “firstproject”  folder, which is the project root , you can see the file “manage.py” and another folder of the same name/configuration root  as shown below:

/firstproject # the project root/container
manage.py # command line tool to manage the project
/firstproject #  configuration root
__init.py__ # this file though empty is required for Python to recognize the folder that contains it as a Python package and not an ordinary folder
settings.py # module level variables for setting / configuration file for the project
urls.py #  url-configuration file  
wsgi.py # configuration for deployment.

We can check whether our environment is ready by executing

python manage.py runserver

You can see the following message:

Performing system checks...
System check identified no issues (0 silenced).
You have unapplied migrations; your app may not work properly until they are applied.
Run 'python manage.py migrate' to apply them.
 
July 01, 2017 - 15:50:53
Django version 1.11, using settings '.settings'
Starting development server at http://127.0.0.1:8000/ 
Quit the server with CONTROL-C. 

Have a look at the diagram below:

It is reiterated that both “django-admin” and “manage.py” are Django’s command-line utilities for administrative tasks. You can do with Django-admin, any task you can do with manage.py; but for using ‘admin.py’ within a project you have to set the environment variable DJANGO_SETTINGS_MODULE or pass   --setting as command line option. The manage.py automatically takes care of those things for you. So the Django documentation authors have opined “Generally, when working on a single Django project, it’s easier to use manage.py than django-admin.”

Difference from other frameworks: The mechanisms for tying together a request’s URL and the resulting response are key to any Web development framework. In the earlier action-based web frameworks we have seen, Struts or Spring MVC,  a request is processed and the response sent by an action in the controller. It is the controller that interacts with the model and renders the view, using the data from the model. In Django that role is played by the functions in the view and it is the view that interacts with the model and uses that data to render the template. So it is called Model Template View (MTV, not MVC) framework, though HttpRequest->HttpResponse flow is the same. Only the component that processes the request and sends the HttpResponse differs. Django uses a fairly simple, but powerful mechanism-URLconf- which enables you to map regular-expression-based configuration items to Python view functions/methods, as well as link these lists of mappings together by including them within one another.

Application

Django distinguishes between a project and an application. A project can contain more than one application.  As shown above, we have to use “django-admin”  to obtain the project/infra-structure files and can use “manage.py” to create and manage the applications. The application should stand on its own and its dependence on the project files should be minimal. In fact “Writing your first Django app part 7” in Django documentation is on how to segregate an Application from a Project and the extra steps required to deploy it separately.  

At-first we will create some small app that serves a static web page when the user makes a request. It is reiterated that Django is an over-kill for smaller apps but we can start learning it through such applications.In the command prompt change to firstproject/project root and  Execute

python manage.py startapp firstapp

You can see in the generated “firstapp” folder among other things the files “models.py”  “views.pyand the Python package “migrations”. We will see “models.py”  and “migrations” in the next article on the “Model” layer in Django. Though in Django it is the view that processes a HttpRequest and renders HttpResponse , the relevant data for a requested page is stored in a Model and the view uses a template to render the response. We will cover template along with view in this article and cover model in the next article.

We can open the project in an editor and complete the generated “view.py” in the “firstapp” folder as under:

/firstapp/views.py

from django.shortcuts import HttpResponse

# Create your views here.
def index (request) :
return HttpResponse ("This is my trial Django app!" )



You can see the index() function takes request as parameter and returns a string as HttpResponse. We can create ‘URLconf’ of the application in the file ‘urls.py’ in our “firstapp” folder. Creating a separate “urls.py” for the application is for the purpose of reducing the dependency of the application on the Project. The file may be completed as under:

/firstapp/urls.py

from django.conf.urls import url   #   ---1)
from . import views
urlpatterns = [   #---- 1)
url(r'^$', views.index, name='index'),
]

  1. The urlpatterns variable is a Python list of the above imported url() method. The method takes the following  “arguments”—1) a regex, 2) a view function, 3) an optional argument dict—and 4) another optional, named argument: name. The name is simply a string, which should be unique among all your URLs; then, you can use it elsewhere to refer back to this specific URL. In regular expressions the “^ “and “$” characters mark the beginning and the end of string for which checking has to be made. The check is made only for the navigation address after the “host:port” and if it matches, then the url-request is forwarded  to the specified view function.

For this separate URLconf of our application to become operational, it has to be “included” in the URLconf of the project. So we can modify the project ‘url.py’  file as shown below:

/firstproject/urls.py

from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^first/ ’, include('firstapp.urls’), ]# code added to include our app url ---1)

Why the above step is necessary? When somebody requests a page from our website ‘firstproject’, Django will load the module “firsrproject.urls”  because it’s pointed to by the ROOT_URLCONF in ‘settings.py’. The  URLconf finds a urlpatterns list there and it traverses the “url”() objects /regular expressions it contains in order. Note that the regular expressions in this example don’t have a $ (end-of-string match character) but do include a trailing slash. Whenever Django encounters include() (django.conf.urls.include()), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing. The  “$” is omitted as  the URL item designed to include other URLconf files is not the final URL, but only part of one.

You can test the urls by running the application. We have to do one more thing before running the project. In the “settings.py” of our project file add our “firstapp”  in the INSTALLLED_APP. After addition that portion may look as under:

/settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'firstapp',
]

Run the project
You can run the server as mentioned earlier and navigate to localhost:8000 in the Browser. The Browser may appear as in Figure-1 given below:

If you add  /admin to the navigation address you may see error as shown below, as we have not yet configured admin interface for our app.

Figure-2

Templates; A Django project can be configured with one or several template engines (or even zero if you don’t use templates).Django ships built-in backend for its own template system,  the Django Template Language (DTL),and for the popular alternative Jinja2 ,which in the opinion of many is an improvement over DTL. Back-ends for other template languages may be available from third-parties. The settings.py generated by the “startproject” command defines Django Templates as backend. Our application can make use of this and our index() function can render a Template/HTML page instead of a string. We will see how to do the same.

   We should create the template/ html file in the templates folder of our app, as in “settings.py” the default configuration is

    Templates = [...., ....., “Apps_Dirs”:True, ....]

 Create a folder “templates” and a sub-folder ”firstapp ”-the same as that of our app. This is for the purpose of creating a namespace and avoiding possible conflict later-on. Code ‘index.html’ as under:

/templates/firstapp/index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Django Learn!</title>
</head>
<body>
<h1>I am Learning Django!</h1>
</body>
</html>

Django documentation says that the Django Template system is not embedding Python in HTML as in other languages (probably it refers to embedded Ruby(erb)

The Django template system provides tags which function similarly to some programming constructs – an if tag for boolean tests, a for tag for looping, etc. – but these are not simply executed as the corresponding Python code, and the template system will not execute arbitrary Python expressions”.  Only the tags, filters and certain syntax features are supported by default -although you can add your own extensions to the template language as needed.

The modified ‘views.py’ to render the template is given below:                                                

/firstapp/views.py

from django.shortcuts import render

# Create your views here.
def index (request) :
return render (request, 'firstapp/index.html') # -----1)



  1. 1) To the render() function, the  request object and the template file are passed.

A dynamic template:
In the earlier sample, our template was just static HTML , though by using a template we were able to separate the design of the page from Python code. A template can have placeholders and various bits of basic logic (i.e., template tags) that regulate how the document should be displayed. We can note that for a display variable, double brackets {{}} are used, and for an action tags that will be executed such as a condition or loop, we have to use {% %}.Our “index.html” can be modified as under:

‘templates/firstapp/index.html


<html>
<head>
<title>
Hello World Django
</title>
</head>
<body>
<h1>
Hello World Django
</h1>
<article>
<span> {{my_var}} </span>   # a variable
<br />
<span>
{% if years < 10 %}          #conditional logic
You are a children
{% elif years < 18 %}
You are a teenager
{% else %}
You are an adult!
{% endif %}
</span>
<br />
<ul>
{% for city in array_city %}   # loop through an array
<li>
{{ city }}
</li>
{% endfor %}
</ul>             

        </article>
</body>
</html>

The  python code in the index() function in “views.py” has to be modified to pass values to the variables to the template . Look at the code below:

/views.py

from django.shortcuts import render

# Create your views here.
def index (request) :
my_variable = "Hello World !"
years_old = 15
array_city_capital = [ "Chennai", "Bangalore", "Hyderabad" ]
return render (request, 'firstapp/index.html', { "my_var":my_variable, "years":years_old, "array_city":array_city_capital})  #-----1)

  1. To the render() function, apart from the request object and the template file name, we pass a dictionary/ ‘context’ that holds data. A context is simply a set of variables and their associated values. The template uses this to populate its variable tags and evaluate its action tags.

When you run this app your Browser may look as under:

Conclusion:

To understand the basics of Django, we saw how to start a project and start a small web application within the project.  Django is a high-level framework with a lot of features baked-in. But basically it is an implementation of HttpRequestàHttpReponse pattern like other action-based frameworks like Struts or Spring MVC. There is also a  difference. Those frameworks used actions in the controllers to process requests. Django uses the functions in view module or class to process the requests. There is no difference in the requestà response flow and only the component that does the job differs. We also saw how Django uses URLconf to map an incoming request to a handler. A URLconf maps URL patterns (described with regular expressions) to views. Django also has good template system which allows the use of placeholders for values and action tags to have some basic control structures to generate dynamic pages. There is one more aspect to the template system which we did not see.-template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override to fill in with content. Thus all pages in a web app will have a uniform look. We will see the same in our next article. If you are not satisfied with the Django template system, Django enables you to create your custom tags. It also allows you to use third-party template library such as Jinja2 or any other template library. Django is has a built-in ORM and a migration tool. The integrated model layer can make use of the same. We will see the same also in our next article








Added on July 28, 2017 Comment

Comments

#1

Sumant S commented on July 28, 2017 at 10:32 p.m.

I am thinking of learning this Django framework. It is very much interesting built on Python. Thanks for the article.

#2

Rashmi commented on August 2, 2017 at 4:13 p.m.

Great website. I like the technical articles.

Post a comment