Introduction to Django – Part 3

In this post I am going to show how to create a web app with Django using Visual Studio. The default files and folder structure of Django.  I already explains some basics of Django and how to install Python tool for Visual Studio in my previous post. If you missed out please read Introduction to Django – Part 2.

Lets start and build a very simple web application, but before that you need to install Python version 3.x and Visual Studio tools of python. If you are going to use IDE other than Visual Studio than please check its prerequisites. Create a new project in Visual Studio and in the new project dialog I will select Python –> Blank Django Web Project template. This project template will create an empty web app which is good for learning purpose. You can also select Django Web Project template from the new project dialog box of visual studio but that will automatically create admin pages and default setting for you.  Once you click Ok after selecting the ‘Blank Django Web Project’ template (I name the project HelloWorld), a new dialog will appear which is telling you that new packages are required for this project and where to install. As you can see in the below Image 2, there are three options,

  1. Install into a virtual environment
  2. Install into Python 3.4
  3. I will install them myself

The first option is most recommended one, this will install the python packages only for this project environment. The second option will install a package will be common across all the project. This option is not very useful. Because you can’t work on different versions of Django. And further more if you want to use one package only for a specific project you can’t as in the second option the package will share across all the projects. In the third option you can use install the package yourself.  This functionality is same as Vitualenv tool. Which helps to create separate environment for each project.

Img1- Blank Django project
Img1- Blank Django project

 

Img2- Package Installation
Img2- Package Installation

 

Img3 - Select Enironment
Img3 – Select Environment

I selected the first option as you can see in the Image2. Once the option is selected the next window will appear. It requires you to enter the new virtual environment name and select the Python version. While I was writing this post I have Python 3.4 on my machine and I give env name for the virtual environment. Once the project is created you can find the default files and folder structure created in Visual Studio solution explorer, as you can see in the Img4 below.

Img4
Img4

Image 4 above show you the default files and folder structure. The python environment node shows the packages installed for this environment. The HelloWorld folder is our project name. The project folder contains the following files,

  • _init_.py: This is an empty file tells Python that this directory should be consider as Python package.
  • setting.py: This file contains all the configuration required for Django installation.
  • urls.py: URL declaration to write neat and clean Urls for this project will be contain in this file.
  • wsgi.py: This file is an entry point for WSGI compatible web servers.

Outside HelloWorld folder a file manage.py exists. This file is a command line utility which allows to interact with our project in various ways. I just give a brief introduction to these files, but later on I will explain in detail about these files.

Lets create our first app. But before that you have to understand the difference between a project and an app. An app in Django language is a web application, which can perform different things like weblog, polls etc. Django apps are small libraries which are representing a single task of a project. Apps can be internal to the project and will never be reused or can be reused in multiple projects. A project is made of multiple Django Apps.

Our initial setup is ready to create our first Django app. We already installed Python, Django and our project is created. Because in this app I am just going to show you how to write a simple HTML page, so I am not going to show you how to setup a database. But later we will discuss this in detail and learn how to create database and how to perform CRUD operations. Open up a command line by right clicking on the HelloWorld project file as shown in the Img5 below,

Img5
Img5

I called app as MyFirstApp, type the following command in the command window this will create app with default files,

python manage.py startapp MyFirstApp

Open the Visual Studio solution explorer and click on show all files and you can see the app folder is created by not included in the project.  Right click on the MyFirstApp folder and include in project as show in Img6 below,

Img6
Img6

Once the app is included in the project you can see that default folder structure and files are created for the app. In my future posts I will explain all the files by default added in the app and what are there purpose. But right now just to see the output of the app I will create a template folder under MyFristApp folder. Under this folder we will add a HTML page to show our output. But first I will show you how the request is routed in Django. Lets create and HTML response once we get an request. Open the views.py file under MyFirstApp folder. And modify the file and shown below,

from django.shortcuts import render, render_to_response
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.template import RequestContext;

# Create your views here.

def MyFirstApp(request):
    return HttpResponse('<html><head><title>My First App</title><body><h2>Welcome to Django world!</h2><p>This is my first Django app</p></body></html>');

If you look into the above code the first three lines, I included the django libraries for HTTPRequest and HTTPResponse. And then we define the HTTP response.

The next things is to define the URL routing. Open the urls.py file of the project HelloWorld and add the following lines,

from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
                       url(r'^MyFirstApp$','MyFirstApp.views.MyFirstApp'),
)

In Django we used Regex statements to write down neat and clean URLs. Once a request is received Django loads the root URL Configuration file. And run through each pattern, which ever is first match Django call the given view. Don’t worry I will explain in depth about Django URL config file. As of now if you can see if a request comes which contains the work MyFirstApp, Django will load the MyFirstApp module view to get the HTTP response back. Next thing to register our module, open the setting.py file at the root folder and scroll to find out the Installed_Apps word and add our MyFirstApp module as show below,

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'MyFirstApp'
)

Now our first Django app is ready and we can see the output on the browser. There are two ways to run the Python application in Visual Studio. The first and simple way is to Run the application by pressing F5 or click on Run command button. The other way to run the Python server and then type the URL. I will use the second approach as this can be used with any IDE.  Right click on the project file in solution explorer and then click Python –> Start Server, as show below in Img7

Img7 - Run Python Server
Img7 – Run Python Server

 

Img8
Img8

This will run the server on the default IP address and port. Which is 127.0.0.1:8000 as show in Img8 above. Type following URL in your browser http://127.0.0.1:8000/MyFirstApp  and see the output.

Img9
Img9

You can see the output on your browser, lets add a page and then return the page in repose of HTTPRequest instead of direct HTML tags as we did. Create a page index.html in the template folder we created. And the following HTML in the page,

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>My First App</title>
</head>
<body>
    <h2>Welcome to Django</h2>
    <p>This is my first Django first app</p>
    <p>And this my first app page.</p>
</body>
</html>

Now instead of returning HTML tags we will return the page. Open the views.py file and modify it, so that it should look like as below,

from django.shortcuts import render, render_to_response
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.template import RequestContext;

# Create your views here.

def MyFirstApp(request):
    #return HttpResponse('<html><head><title>My First App</title><body><h2>Welcome to Django world!</h2><p>This is my first Django app</p></body></html>');
    return render_to_response('index.html');

I commented the HTTPResponse line and write down render_to_response(‘index.html’) . As I previously explained that Django is based on MVC format and as you can see that how easily we change the view source. We just modify the views.py file and the output is coming from an HTML page. I hope you get the idea how Django is working. Although there are many things which require explanations. But the purpose of this post is just to get the idea how to write a basic app in Django. Next we will explore the Django in detail and then I will explain each and every file which is created by default and the most important is how to create a DB connection and creating models.

You can download the source code from here.HelloWorld

Leave a Reply