Thursday, January 30, 2014

Creating models

Now we have a UI up and running, but we need a powerful and reliable backend for providing and extracting data. As I said before, I'm assuming knowledge of SQL syntax. Also, as I said earlier, we'll be using SQLite3, and then upgrading to MySQL.
Now open your mysite directory. You should see a database file named trial.db. Now change into your website directory. Open the models.py file.
We're creating this basic project to mirror a college website. So let's create three classes of people: students, teaching staff and non-teaching staff. We'll create a separate class for each.
Type the following code in the models.py file.

from django.db import models
class Student (models.Model):
    name = models.CharField (max_length = 20)
    roll_no = models.IntegerField (max_length = 5, primary_key = True)

As you can see, I created a Student with a name and a roll_no (roll number). Also, I declared the roll number as a primary key. Now let's create the teaching and non-teaching staff.

class Teaching (models.Model):
    name = models.CharField (max_length = 20)
    id = models.IntegerField (max_length = 5, primary_key = True)

class Nteaching (models.Model):
    name = models.CharField (max_length = 20)
    id = models.IntegerField (max_length = 5, primary_key = True)

As you can see, I replaced roll_no with id. The definitions of all three have the same data types, but different fields. But, being familiar with SQL, you'll know the difference. Now come out of the website directory into the mysite one and run the following command:

python manage.py syncdb
You should see something like:

Creating table website_student
Creating table website_teaching
Creating table website_nteaching

This means that all the required tables have been created.
Now, to check if everything is working once more and also to add some base users, run the following command in the terminal from the mysite directory:

sqlite3 trial.db

This will open up the trial.db file with the required tables. Enter some values in the website_student, website_teaching, and website_nteaching tables as you want. If the above command issues an error, it most probably means that sqlite3 has not been installed on your system. Try:

sudo apt-get install sqlite3

If this does not work, install it through the Software Center or its equivalent in Unix systems, and for Windows, I'm afraid, you'll have to search for yourself, as I'm also currently working on Ubuntu and have no inkling as to how to do this in Windows.
In the next part we'll see how to manipulate data in the database from Django.
Cheers!

Saturday, January 11, 2014

Views

Now that we have created our admin page, we'll move on to adding webpages to our website. Feel free to tinker with the admin page, django offers amazing tools for admin documentation and control. But more on that later.
In our website, when someone clicks on a hyperlink, or does some action (specified by us) that triggers a URL change, they should be redirected to a new page. Creating this new page has two aspects: 1) Creating the user interface (in the views.py file)  2) Creating a custom URL to guide the user to that page.
As I mentioned earlier in this tutorial, I'm assuming a rudimentary knowledge of HTML, PHP, JavaScript and other web design tools. With that in mind, we'll dive straight into the GUI design.
Let's design our homepage first. Open the views.py file.

Type the following on the first line:
from django.http import HttpResponse

HTTP stands for 'Hyper Text Transfer Protocol'. The HttpResponse () function will render whatever HTML/PHP/JavaScript/CSS code we write onto the browser to make a GUI.

Now type the following code:
def home (request):
      someCode = """
      <html>
         <body>
            Hello World!
         </body>
        </html>
       """
       return HttpResponse (someCode)

Now your homepage is all set to display the ageless 'Hello World!' message. Note: The 'request' parameter is very important.
Now that we have our GUI up and running (I know it's not very impressive but you can add beauty later. Right now what we need to focus on is redirecting) we'll proceed to step 2: creating a URL.
Open the urls.py file and type the following code:
url (r'^home/', 'website.views.home'),

This code will tell django that if the URL 'localhost/home' is accessed, the code in the function home() in the app website's views.py file is to be used as GUI.
The r'^' is a part of UNIX regular expressions, about which you can read up online. But in depth knowledge of that is not required here. r'^' indicates that in localhost/home, 'localhost' can be replaced with anything (when it is deployed on the server) and the result won't change. You can put your site's domain name in place of that.
Now when you type http://127.0.0.1/home/ in your browser, you will see this 'Hello World!' message.
That's all for now! 

Wednesday, January 8, 2014

The basic admin page

Okay, now that we have created a project, let's proceed to the actual programming. Open the folder named 'mysite'.
cd mysite

We will initially use SQLite as our database engine. Although it is much less powerful than MySQL, it is easy to implement and convenient for testing. We can then upgrade to MySQL

In the 'mysite' directory, create a file called 'trial.db'. This is the database we will be using.

Open the 'settings.py' file. On line 14, in DATABASES, set 'ENGINE' to 'sqlite3'.
'ENGINE' : 'sqlite3'

In 'NAME', give the path to your 'trial.db' file.

Now scroll down to line 115, in 'INSTALLED_APPS'. You will see two lines saying 'Uncomment the next line...' Uncomment the lines under both the comments.

In the same INSTALLED_APPS, add the line 'mysite.website', This line will tell django that website is an app that is to be included. DO NOT FORGET THE COMMA.

Now go to the file called 'urls.py'. Uncomment lines 4, 5, 13, and 16.

You're set! Open the terminal, and type the following:

python manage.py syncdb

This command tells django to synchronize the database. It will ask you to create a super user. Do so. Run the command again. This time you will see a far shorter number of lines in the terminal. Once this is done, type the following:

python manage.py runserver

This command starts the development server on which we shall see the execution of the code. It will tell you to go to http://127.0.0.1/, which is localhost. Go to that url and you will see a success message.
After that, go to this url:   http://127.0.0.1/admin/

You will see a login page. Log in as the super user you created earlier for the syncdb command, and you will be redirected to a control panel.

That's all for now! Feel free to ask doubts in the comments. I may have left something out. You can also send me an email on the id specified. Adios!

Friday, January 3, 2014

Creating a project

You can download Django from the official website or search for OS specific downloads on the internet.
Let's create a sample college website complete with user login and a student database.

To create the project:

django-admin startproject mysite

This command will start a project called 'mysite'. If you open the folder labeled 'mysite'  you'll find the following things:
  • __init__.py: This is the initialization file. There is normally nothing in this file, and your app will work very well if you keep a cool, wary distance from this file.
  • manage.py: This file issues commands for running the development server, setting up and synchronizing the database etc. Again, this file is not to be altered.
  • settings.py: This file is going to be altered a lot by us. This contains all the settings for database selection, application listings, middleware classes etc.
  • urls.py: Another file that will be altered heavily. This file contains all the URLs that our website will contain and their specific webpages.


Adding applications:
The part up till now was only the project skeleton. We need to add apps to our website to make it more useful. Technically, you can have the entire website up and  running with a single app, but that's messy and a bad practice. Here, 'app' doesn't meant much the same thing as everyone knows. As we progress with the tutorial, the meaning will get clearer.

First, change into the project directory.
cd mysite

Then, add your app.
django-admin startapp website

Now, if you enter the folder labeled 'website', this is the list of files that you will see.

  • __init__.py: Again, initialization file and not to be tampered with.
  • models.py: In this file you will be defining the tables in sql that you will be using in the form of Python classes. Django knows how to translate these classes into sql tables in the appropriate form.
  • tests.py: This file is used for designing tests for the code. Many times, to check if a particular webpage is working, you have to navigate through a labyrinth of other pages to get to the desired page and look for bugs. This file automates this process, thus reducing developer effort.
  • views.py: This file is responsible for the user interface on the webpages. Here we will be using CSS, JavaScript and other languages to make our webpages more attractive.


That's all for now. We will start implementing our website in the next part of the tutorial.

Introduction

Django is a web framework that can be used to design websites in Python. It's lightweight, easy to learn and can incorporate scripts from several other languages like MySQL, JavaScript, HTML, CSS, PHP etc.
This tutorial assumes that you have a basic knowledge of Python syntax, webpage design in HTML and SQL syntax.
Keep checking for further posts.