Wednesday, September 25, 2013

Crash Course in Django - Part 2 : Step by Step Guide to Make Django App Real Quick

Introduction :  In  first part we covered the basics of creating objects , saving and retrieving them from database. In this series we will try and extend it further with a user interface and setting it all up -Lets try and create one employee listing ( Refer part 1 for the Employee Problem ) interface where all the companies employee are listed and can be searched by name. This will a step by step tutorial to make a django application rapidly and will also try and integrate various other technologies like Jquery , Twitter bootstrap etc with Django Templates. Lets start again with the bullet points:

Tip : 
  • There are two ways to handle this ride
    • You can get the code from here and start walking through each point  to make it real quick. With all files in place you can just cruise through 
    • Or you can start step by step with thought process and start creating your files and verifying the changes made with mock ups and gist file changes posted after every essential step
  • Now which step to choose depends - again on how quick is quick. 
  • Last , please don't forget this is not a series on Jquery , User Interface or html layouts etc. they are just there to fit the purpose 
Get Geared: 
  • Lets create a mock up first  - how our interface will look like 

  • For creating this form we would be using twitter bootstrap  and the corresponding html will look as shown below

  • In real world application I would remove the side pane of employees listing with link button for detail as we can show all the employees present with click of search button with no parameters. The side pane is included in this article to show some of the Django template language features. 
  • Lets quickly start creating the project structure 
    • Create Project : $ startproject demoapp
    • Add Postgres option in as database
    • Add demo app as in INSTALLED_APPS section of
    • Add file to demo app sub directory and add the Employee class we discussed in part one. The screen shot below shows the changes we made

    • From the command prompt in the Project directory where file is present call
      $ python syncdb and we will see the message like  which will also create a table in the database. When we call syncdb for the first time django asks us to create one admin login - create one. How to use admin login we will cover later in the series for  now lets focus on the task at hand

  • Now if we want to check if  things are OK , lets learn a new utility from the command prompt type the following: $ python shell . This will open a command prompt in context of the current project. So if want to check the database connection type 
    • $ from django.db import connection
    • $ from django.db import connection & cursor = connection.cursor(). If no error then we are able to connect to the database
  • We can similarly use shell to import Employee object and ORM functions to check the status of our code. For example
    • $ from demoapp.models import Employee will import Employee
    • Employee.objects.all() will return blank as we don't have and employee yet
  • Lets add some Employees from the console itself
    • emp = Employee(employeeid=124,name='Mathew',dob='1980-1-11',salary='5423.4') &
    • emp = Employee(employeeid=1004,name='James Holmes',dob='1970-10-21',salary='7000') &
    • emp = Employee(employeeid=14,name='Monica Hilton',dob='1986-07-10',salary='3000') &
    • Employee.objects.all() will now return a set of 3 employees
  • We can do a batch save but lets leave it for advance use cases
Lets try and get our html page up & running now with our back end almost ready lets hit on layout part
  • What kind of URL we want to expose to our Employees - something like below will do for now
    • url we need :
    • Lets add  url(r'^employees/',get_all_employees) the file  and corresponding get_all_employees view to file. The changes will look as shown below for both the files 
  • But before we load our html some changes we need to make to file and we need to have some understanding of how Django Template Engine work
  • As we know Django view returns a HttpResponse object and we also tried passing string and JSON to it.  How about giving one well constructed html ? We can do that using Templates . So create a html file and replace the dynamic content - like user name , in our case employee name with variables with double braces {{variable_name}}
  • For example my Html says <p>Welcome James !<p>  where James is the name of logged in user and will keep on changing for each logged in user we assign a variable to this and change it like  <p>Welcome {{USER_NAME}} !<p>  and we will pass o a USER_NAME variable to the Template from our view using render_to_response function. render_to response is standard django function that takes the name of the template - html file as first argument and dictionary as second argument. In the above example the render_to_response will be like render_to_response('User.html',{'USER_NAME':Computed User Value})  and the  Django Engine when renders it will replace USER_NAME in html to the value that we have passed. If you want to read more on this please refer here .
  •  For our rapid learning purpose whatever  values we want to pass or show in html pass them via render_to_response django function as KEY-VALUE pairs . Use the KEYS on html file which will be replaced by values while rendering. This html file is our Template. 
  • Two more things that can come handy while creating Templates - if / else statements on the passed variable can be used within the html file like
    • {% if VARIABLE_1 == TEST_VALUE  %} <p> Good Results </p> {% else %} <p>  Bad Result </p> {% endif %}. Django Will now selectively render html based on the TEST Value and VARIABLE_1 comparison which we pass from backend
    • {% for item in item_list} <p> item.attribute_name </p> {%endfor%}. This will be used to parse list of object and accessing the value inside that object by dot operator. As previously said we will pass this item list also from backend
  • So in our case we will pass employee list from backend like render_to_response('Employee.html',{'employees_list':employees_list})  and parse it in the html file for creating the employee list. The side pane of employees we see in the html gets generated like: 
  • Please note the way we are passing Employee Id to Javascript function - This will be used to fetch employee detail once employee is clicked
  • Last setup change - how will Django know where to pick the template from - there is a TEMPLATE_DIRS  tag in and there we will give the path of the folder where we will keep our Employee.html  , which is  TEMPLATE_DIRS "demoapp/templates" . And  for loading the static file one needs to provide STATIC_URL = '/static/'  and append the <script> </script> , link style sheet  load  directives in html as below. Don't forget to create one static folder in demoapp folder just at the level we have template folder and put the bootstrap folder ( js, css, img folders inside it). So django engine will look for static folder as defined in STATIC_DIR and append the paths to load the javascript , css and other resources 
    • Also add load static files directive to tell Django Engine to do so {%load staticfiles%}
    • <script src="{% static "bootstrap/js/bootstrap.js"%}"></script> 
    • <script src="{% static "bootstrap/js/jquery-1.7.2.js"%}"></script>
    •  <link rel="stylesheet" type="text/css" href="{% static "bootstrap/css/bootstrap.css"%}"/>
  • So create on templates folder inside the demo app folder and place the Employee.html file there
  • Try running the server with python runserver command ( runs the application in default development server )and type  on the browser . The html we made will show up. Along with the list of Employees we have in the system

  • We now have two problems to solve - 
    • On click of employee Employee detail should render on the right pane
    • Implementing employee search
  • For first we will implement get_employee_by_id view on  the server. Map this view with corresponding URL and call this URL via jquery GET function and then parsing the returned data to be placed in the form. ( As this is a Django Series -Not talking much about the JQuery bit here , please Google about JQuery Ajax calls. Please note how we mapped the URL in Jquery Ajax call to the file. See onEmployeeClick function below for javascript code 
  • For second - Searching employee by id is same as getting name of employee and other details we discussed above via employeeid. I will talk more about Search by name because searching by Id will always return one employee but seaching by name might return more so search functionality will try and place result in row order using twitter bootstrap. Please refer the code below for the same.See onEmployeeSearch function below for javascript code
  • And now the mapped url and views changes :
  • Now we can download the whole code and compare the changes  from the repository here
  • Some files  come by default when django creates an app like and The later one is used in deployment scenarios that we will cover later ..
This brings us to end of this part and I guess we are good to go ....

No comments:

Post a Comment