Monday, September 23, 2013

Crash Course in Django - Part 1 : Django Basics

Introduction :  This is first  lecture for people who want to learn Django rapidly. This assumes some familiarity with Programming of Web based application but not mandatory. Here I will try to be as generic as possible and will try and redirect the reader to specific as and when needed.  And as true for all the matters of interest - there is Google. So lets start bullet point approach to quickly get us going for Django based web development.

Gear Up : 
  • Install Django :  Install Django as mentioned in the Documentation here. The installation is fairly straight forward both on Windows and Linux based OS.
  • You need a Data Base - Django comes with SQLLite Database for practice purpose but I suggest you either install MySql or Postgres. If you are not using the inbuilt SQLLite database you also need to install connectors for same. Find more about connecting to various databases here. I am not repeating it here because all this is fairly well documented
  • When you are up and running with basic setup of Django start by creating a new project by typing the following command on the command line:  
django-admin.py startproject demoapp
  • Demo App is a name of the directory and will contain manage.py file. This is the file that is used by Django to deliver its magic. ( More on this later). The command will also create a directory structure as 
demoapp/
    manage.py
    demoapp/
        __init__.py
        settings.py
        urls.py
        wsgi.py
        models.py ( This is file we will add later. Not by default)
        views.py ( This is file we will add later. Not by default)   
  • Django Follows MVC pattern to achieve separation of concerns. Like the way we have Controllers in the MVC pattern to take care of logic, Django call the controllers as views. These views are collated in one file named as views.py. So any function you can think of like addition of two integer or a function to sort and return certain data set, will be written in views. View is nothing but a function that takes certain argument -request and givens certain output - HttpResponse
  • The constrain with view is that it should always return HttpResponse type of object. So even if we want to return a string or JSON, put it inside a HttpResponse object like 
  • As shown above view has a default argument as request - this is nothing but a HTTP request object which can be used to access variables from URL or from the html form being submitted. Also it returns HTTP Response. In a nutshell use the request object to get the data out of html form. Use the HttpResponse to render data on the form. Django comes with a template language which can be used to render calculated variables on the form. Will be covering Django Templates in later part of this series
  • Next file of interest is urls.py , this file is nothing but a collection or a map of url and function ( Django view ). Its a way to tell the Django Engine - if a URL of specified type ( this also includes regular expressions) comes as a request on the server , redirect it to the view specified in the map. From there on the view takes care of processing the HttpRequest object and rendering a HttpResponse
  • Essentially URL.py is a file where pattern in URL is matched and appropriate function is called from the views.py file. So if the incoming request is like http://127.0.0.1:8000/get_units , Django Engine will match it to  first URL entry and will call get_units function from the view which will in-turn return the JSON object we talked about earlier
  • So till now - views.py contains  logical bundling of function that operate on Incoming Request  and urls.py  helps that request to reach the suitable function. Question is where and how we get and manipulate data from ? After all its not only about rendering the incoming request to a Django Template
  • Comes in the frame models.py file - This is the file that contains all the data holders we need to get and manage data from database system. A model is in-program representation of Data Tables in the Database. Lets take an example on this - consider the application for creating a Employee List
  • Employee List application will  store employees detail in the database - lets assume our employee has four attributes and attribute type
    Attribute NameAttribute Type
    Employee IdInteger
    Namestring
    Date of Birth Date Time
    SalaryFloat
  • In the Database this will be employee table & in django this will map to employee model as 
  • For legacy databases - use db_column attribute to map each and every table column with Django Model and use Meta tag to map the table as shown above. For fresh implementations call python manage.py syncdb and Django will create all the tables for us
  • Once the model is created we can use Django ORM to directly work with Employee Objects , which in-turn will interact with database. For Example if we would like to do following operations on our Employee from our python view ( remember all the logic and action is in views.py) import the employee model in the view and call the CURD functionality directly using Django ORM. 
    Creating Employeeemp = Employee(employeeid=124,name='Mathew',dob='1980-1-11',salary='5423.4')
    Saving emp.save()
    Get All employeesEmployee.objects.all()
    Get Employee By idEmployee.objects.get(employeeid=124)
  • Once we have reached so far we can easily manipulate on data sets in data base using Django ORM to put it all together lets try and see how one will implement a URL -  http://127.0.0.1:8000/get_employee?EMPID=124  API using whatever we have discussed where EMPID is passed a Query string parameter to the view
  • Last - settings.py is the file where one keeps all the configuration info regarding the web application - like data base settings . logging , application to include , admin module etc. 
  • This brings us to the end of this part. Hope we are good to go ! 

No comments:

Post a Comment