First App With Django

In this article, we will just not add some functionality to it but will also learn a few more things about Django.

So, here I am again reporting for duty with my third article of the Django series. So far we have created a dummy project. In this article, we will just not add some functionality to it but will also learn a few more things about Django.

A few more things about Django

We have talked about Django being an MVC framework. However, the controller in MVC is ‘view’ and view in MVC is called ‘template’ in Django framework. The view is actually the component which retrieves and manipulates data and templates present this data to the user. That’s why Django is more known as “Model-Template View or MTV” framework. Using another terminology does not change the fact of Django being an MVC framework nor does it affect the development of the application. The difference between the two frameworks can be explained as follows.

 

 

Knowing this, let’s start working on our app.

Views and URLs

We saw the welcome page of our development server but it was too typical and the first thing that came to my mind was how can I change it. If you thought the same then don’t worry that’s exactly what we’ll be doing. In order to do this, we will create an ‘entry point’ for our application. This entry point would be in the form of URL. This URL would tell Django to display our very own welcome message whenever a user accesses this URL.

Creating the Welcome View

Django defines a view as a regular Python function which would respond by generating the corresponding page as per the request. To define our view, we first would have to create our Django application inside our project. The application is more like a module inside our web that would perform a certain task. You can think of it as a container for views and data models. To create the application, issue the following command within our website folder:

  1. python manage.py startapp webapp

Does that seem familiar to you? Yeah, we used pretty much same syntax for project creation.

What this syntax does is it used startapp as the first parameter to python manage.py, and provided web app as the name of our application.

This command will create a folder named web app inside the project folder with the following files:

migrations

Whenever we make a change in our database, for example create a table, define another field or drop a table, we have to apply migrations to let Django know that we want these changes to happen. This folder will contain all those changes. Django migrations module is more than just a way of automatically generating and applying SQL statements, it’s also a transparent API to write your own database changes in Python. It comes with wheels for those who need it (or trust enough) and tools for those who like to get their hands dirty. We will experiment with migrations later.

__init__

Same as the project creation, this file doesn’t contain any code and is there to tell Django to treat the folder whole as a package.

admin.py

We already have talked about the admin panel. This file is used to display our models in Django admin panel. So whenever we are creating a new model, we would have to register it in this file.

The code that python created for us looks like this.

  1. from django.contrib import admin  
  2. # Register your models here.  

apps.py

This file is created to help user include application configurations for the app.

  1. from django.apps import AppConfig  
  2. class WebappConfig(AppConfig):  
  3. name = 'webapp'  

Basically, it contains the metadata about our app.

models.py

Database contains tables to store our data. These models maps to a single table in the database. Thus, a model is a single, definite source of information about our data. Whenever we are connecting to the database to store or retrieve data, we would do it in this file.

  1. from django.db import models  
  2. # Create your models here.  

tests.py

This file can be thought of a bug-killing tool. You can use this file to test a test suite, solve or avoid a number of problems.

  1. from django.test import TestCase  
  2. # Create your tests here.  

views.py

This file will control what the user sees in our app.

  1. from django.shortcuts import render  
  2. # Create your views here.  

For this article, we will only play with our view file.

Now let’s create the main page view. Open webapp/views.py in your text editor or IDE and the following.

  1. from django.http import HttpResponse  
  2. def main_page(request):  
  3. output = '''''   
  4. <html>   
  5.    <head></head>   
  6.    <body>   
  7.       <h1>%s</h1><p>%s</p>   
  8.    </body>   
  9.  </html>   
  10. ''' % (  
  11. 'Hello World',  
  12.    'Welcome to my first Application in Django',  
  13. )  
  14. return HttpResponse(output)  

Let’s go through our code,

  • We import the class HttpResponse from django.http. 
  • We define a Python function that takes one parameter named request, build the HTML code of the response page, wrap it within an HttpResponse object and return it.

Django views work the same as regular Python function. It takes user input as a parameter and returns page output. Before actually seeing our added functionality in action we will have to connect it with URL.

Creating the URL

We have talked about the urls.py file while discussing the project files. Go ahead, open it and edit it as follows.

  1. from django.contrib import admin  
  2.  from django.conf.urls import url  
  3.  from webapp.views import *  
  4.  urlpatterns = [  
  5.    url('admin/', admin.site.urls),  
  6.    url(r'^$', main_page),  
  7.  ]  

Again let’s break down what we did.

  • The file is importing url from django.conf.urls.
  • We imported all the views from webapp.views.
  • The urlpatterns function is used to define the URL table. It contains two mapping for now — one was pre created; admin; second from r'^$' to our view main_page.

There are two things to note about our defined url. It is a raw string that contains two characters, ^ and $. Python’s way of defining raw string is r ‘’. By raw we mean that anything between r ‘’; even if it contains any escape sequences or backslashes, would be retained rather than interpreted in any other way. This is important because regular expressions often contain backslashes. The other thing is the format of our regular expression. In Django, urls are defined as regular expressions. In regular expressions, ^ means the beginning of the string, and $ means the end of the string. So ^$ basically means a string that doesn't contain anything; that is an empty string. Given that we are writing the view of the main page, the URL of the page is the root URL, and indeed it should be empty.

Now that everything is set, let’s run and check our first view. Launch the development server. You can either launch it from a command prompt by entering the following command.

  1. python manage.py runserver

or just run your application from inside the IDE which will automatically run the server for you. Do as you please. Now go to http://127.0.0.1:8000/ to see the page generated by the view.

 

Congratulations! Your first Django view is up and running.

Let’s explore what’s going on behind the scenes.

  • When you navigate to http://127.0.0.1:8000/, Django searches the URL table in urls.py for a URL that matches the request.
  • If Django found the URL, it calls its corresponding view. The view then returns the generated page wrapped in an HttpResponse object.
  • If Django doesn’t find the URL, it will simply display a 404 ‘page not found’ error.

Our main page looks so simple without CSS and html is also embedded in between the python code. But what if you are working for a company and your co-worker is designing the website whereas you just have to implement that design? Here’s another catch --- your co-worker just knows html and Python is an ‘Alien’ language for him. What would you do in that case?

Don’t worry I won’t leave you alone in such a critical situation. So we’ll separate our html code from Python code in the next article and will also make it stylish. Stay tuned. :)