Monday, 20 October 2014

Adding Foreign Keys in Database Tables of Django Application


To make an attribute foreign in another table, it has to be made primary in its home table.
Lets take an example of two tables named "primary" and "foreign".

class primary(models.Model):
       name = models.CharField(max_length = 30)
       id = models.CharField(max_length = 30, primary_key = True)

here in the "primary table" , id should be made primary key to be used as foreign key in secondary table.

class secondary(models.Model):
         dob = models.CharField(max_length = 30)
         id = models.ForeignKey(primary)

here,the "id" in the table named "secondary" has been made foreign key by using ForeignKey()  field with name of the parent table of the attribute "id" inserted as its parameter to make "id" as the foreign key in the
table named "secondary".

Playing with Data Retrieval from Databases to Templates via Views

Add the following function in views.py,
#from __future__ import unicode_literals
from django.http import HttpResponse
from django.core.context_processors import csrf
from books.models import Books
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.template.loader import get_template
from django.http import HttpResponse

 def retrieve(request):
         Book_info = Books.objects.get(id = ‘12’)
         All_info = Books.objects.filter(author=’priyanka’)
    books_list = Books.objects.all().order_by('-timestamp')
    return render(request,'loggedin.html',{'books_list': books_list,’Book_info’:Book_info,’All_info’:All_info})


Explanation for the above code:

  1. objects.get( [The condition required] )
If you know there is only one object that matches your query, you can use the get() method on a Manager which returns the object directly.
                                                   Book_info = Books.objects.get(id = ‘12’)
Here, we retrieve information of the book  whose id is 12 and it gets stored in the variable Book_info


  1. objects.filter( [The condition required] )

Returns a new QuerySet containing objects that match the given lookup parameters.
                                                  All_info = Books.objects.filter(author=’priyanka’)
Here we  retrieve information of all the books which match the author name  ‘priyanka’.

Note: filter() will always give you a QuerySet, even if only a single object matches the query - in this case, it will be a QuerySet containing a single element.
where as  get() method returns only one  object that matches the query.

  1. objects.all()
Returns all the objects from the table.
                                         books_list = Books.objects.all().order_by('-timestamp')
Here  book_list variable that contains information about all the books stored in the table but ordered according to the timestamp.
                                                    

We can retrieve the data from database tables in various ways.Please do refer https://docs.djangoproject.com/en/1.7/topics/db/queries/   for the same.




  Now that we have retrieved the data from databases, we can post information retrieved on the templates using render.
                                                   return render(request,'2.html',{'books_list': books_list,’Book_info’:Book_info,’All_info’:All_info})

request indicates the template to which we need to pass on the data retrieved.Here we pass on the data retrieved to 2.html whose creation is explained below.



CAUTION: We can use return render_to_response instead of return render, but in the former one helps in posting only one variable at a time but the latter one helps in posting as many as variables/query sets we need.

If one had used return render_to_response one  had to write three different statements instead of one return render.


To use return render add the following header at the top of views.py
                                 from django.shortcuts import render

Add the following piece of code in urls.py  to connect views.py and template(2.html),


                          from django.conf.urls.defaults import *

                           urlpatterns = patterns('',
                                  (r'^retrieve/$', 'books.views.retrieve),
                                  )




Creation of template(2.html)

<html>
<head></head>
<body>
< - - - - ! Posts the detail of the book with ID 12 - - - - >
  {% for b in Book_info %}
    <p> Name: {{b.name}}</p>
    <p> ID: {{b.id}}</p>
   <p> Author: {{b.author}}</p>
  <p>Purchased time: {{b.time_at_which_it_was_bought}}</p>
{% endfor %}

< - - - - ! Posts the detail of all the books whose author name matches with Priyanka- ->
  {% for c in All_info %}
    <p> Name: {{c.name}}</p>
    <p> ID: {{c.id}}</p>
   <p> Author: {{c.author}}</p>
  <p>Purchased time: {{c.time_at_which_it_was_bought}}</p>
{% endfor %}



< - - - - ! Posts the detail of all the books in the table ->
  {% for d in books_list %}
    <p> Name: {{d.name}}</p>
    <p> ID: {{d.id}}</p>
   <p> Author: {{d.author}}</p>
  <p>Purchased time: {{d.time_at_which_it_was_bought}}</p>
{% endfor %}
</body>
</html>

Playing with Data Storage from Templates (HTML) via Views

To create the templates, add a folder named “templates” under the “books” application. In which create a html name 1.html and add the following code :


<html>
<head>
</head>
<body>
<form action="/name/" method="GET"> {% csrf_token %}
     <label> Enter  Book name </label>
     <input type=”text” name=”t1” />
     <label> Enter  Book ID</label>
     <input type=”text” name=”t2” />
     <label> Enter  Book author</label>
     <input type=”text” name=”t3” />
</form>
</body>
</html>



urls.py is situated under 

Python27
     |
   jango
              |
              testproject
                         |
                         books
                         |
                         testproject
                                |
                            settings.py
                                  |
                              urls.py
                         |
                         manage.py   
                         |
                          test.db

Add the following piece of code in urls.py ,

                           from django.conf.urls.defaults import *

                            urlpatterns = patterns('',
                                  (r'^name/$', 'books.views.data'),
                                  )


Note: The url passed as action  in 1.html is defined in urls.py, which  provides path to  function (def) named data in views.py. Here , “data” is name of function in views.py, which is “books” application.


views.py would be defined as follows with the following code snippet :


#from __future__ import unicode_literals
from django.core.context_processors import csrf
from books.models import Books
from django.utils import timezone
from django.template.loader import get_template

def data(request):
 if 't1' in request.GET and request.GET['t1']:
     name  =  request.GET['t1']
 if 't2' in request.GET and request.GET['t2']:
     id = request.GET['t2']
 if 't3' in request.GET and request.GET['t3']:
      author =  request.GET['t3']

b = Books(name=name,id=id, time_at_which_it_was_bought=timezone.now(),author=author)
b.save()



Explanation to the above code:
We need to import  all the tables  which we will be using in views.py. The above code imports tables from models.py. Now we need to collect all the data entered by user in the form and store in table named Books.
Data entered  in each of the fields of the form is checked to be empty or not, and then collected by using the syntax:  

                                             if 't1' in request.GET and request.GET['t1']:
                                              name  =  request.GET['t1']

The third field “time_at_which_it_was_bought” contains the time at which book was purchased,So we need the current time which is got using timezone.now().
After collecting all data entries we save it by using the following statement:

                                                  b = Books(name=name,id=id, time_at_which_it_was_bought=timezone.now(),author=author)
                                       b.save()

Playing with Django Application and Databases

Creation of Application in Django Python

Continuing with the creation of a project in django from our previous blog on " How to install Django on Windows 7 ", we would like to guide you in  the creation of an application in this blog.


Now that you have created your project named "testproject" ,the following table can help you sync with  the skeleton of the Python27/jango/testproject  folder  present on your system:


Python27
      |
     jango
               |
               testproject
                          |
                          testproject
                          |
                          manage.py

[testproject and manage.py are present in testproject]


 If your django project folders sync with the above respective skeletons , good job you are on the right path!!!!

Now , lets move ahead to create our first django application.

Your respective django projects should look exactly as depicted in the following table , after the creation of the django application.


Python27
      |
    jango
               |
               testproject
                          |
                          books
                          |
                          testproject
                          |
                          manage.py



To do the same , run the following command in your command prompts
                                       
                                          python manage.py startapp books      

You will be able to see that , the newly created django application “books” has been created under the django project (named as testproject  here).   


 
Default contents of Django application on creation     
   On creation of django application , certain files are created as a part of the django application. These are  :
  •    views.py
  •     models.py
  •     tests.py
  •     admin.py
  •     __init__.py


      Skeleton of the entire Django Project




You will be able to understand from the above mapping that the entire django project will revolve around files named views.py , models.py , and the templates. urls.py file ,which is under the testproject folder of the django project, connect the views.py and the templates.


 
Creation of Database


Database is very integral part of any application  so hence , lets go ahead and create
a database for our application.If you already have had a quick tour of the contents of the django project you would have noticed a file named setting.py residing under testproject folder of your django project named testproject.
In settings.py , you will be able to find DATABASES.

                                     



                                              NAME of DATABASES in windows
DATABASES = {
  'default': {
      'ENGINE': 'django.db.backends.sqlite3',
      'NAME': 'C:/Python27/jango/testproject/test.db',
  }
}




Your default database engine is sqlite3 and we suggest you to go ahead with the same instead of meddling with mysql or any other engine.

For the database name , kindly give the entire path of the database you want it to reside in and end the path with the name of your database.


Now create the database just named above, using the following command :
                                                        python manage.py syncdb

On running the above command , you will be able to see the file test.db having been created under the django project(here testproject).

To view the contents of the database created
To view the contents of the database which we will talk about it later , you will have to install the sqlite browser for the same.

use the following link to download it and install the same :
                                     http://sqlitebrowser.org/
Your sqlite browser will look the same as below and one can open the database created (here, test.db) above to view its contents.






      


             How to create the database tables for Django application

Previously we have discussed about the creation of database in Django, using default  sqlite3, now we would like to continue with creation of database tables for Django application named books whose creation has been explained above.

  1. Open models.py  of the django application named books.
  2. Add the following to models.py to get access to Model Fields from django.db
                                       from django.db import models
                             from django.db.models import Model


Refer : https://docs.djangoproject.com/en/dev/ref/models/fields/ to choose the model fields required for your application. Here in books application, lets create a table  named Books , which might require fields such as Book name, Book id, author name and time at which it was bought . The table can be created by adding the following piece of code in models.py of books application:

                             class Books(models.Model) :
                                      name = models.CharField(max_length = 30)
                                       id = models.CharField(max_length=30)
                                       time_at_which_it_was_bought = models.DateTimeField(auto_now_add=True)
                                        author =  models.CharField(max_length = 30)


Following this, move to settings.py under testproject :

Python27
     |
   jango
              |
              testproject
                         |
                         books
                         |
                         testproject
                                |
                            settings.py
                         |
                         manage.py   
                         |
                          test.db

To add books application under installed apps.
               INSTALLED_APPS = (
   'books',
  )




 Move to terminal , to validate the creation of tables
                                                python manage.py validate 

We just wrote about the design of the required database tables in models.py. To run the code and create the tables type the following on the terminal,
                                               python manage.py syncdb