Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

Django Hello World

Hello World is the traditional simple application that prints the message hello world that is used to introduce beginners to a new language. While it prints only a simple message, it is useful in explaining the core concepts of the application flow.

In this section, we will create a simple Django Hello World application that will print the message in a web browser.

Topics to be covered

We will cover the following topics in this lesson

  • How to create a new project in Django
  • Django Project Directories
  • How to create an application in Django
  • The difference between a project and an application
  • Course Project KodeBlog Online Book Store
  • Summary

How to create a new project in Django

In this section, we will learn how to create a new project using the django-admin tool

Open the terminal in the directory that you want to create your project in and create a Virtual Environment for your project. We learnt how to create a virtual environment in the previous lesson.

Activate your Virtual Environment then run the following command

pip install django

or the following command on machines that have both Python 2 & 3

pip3 install django

HERE,

  • The above command installs django in our virtual environment

The sytanx for starting a new project is as follows

django-admin startproject projectname

HERE,

  • django-admin startproject projectname uses the utility django-admin to run the command startproject which creates a new project called projectname.

You can now run the following command to create a new project called helloproject

django-admin startproject helloproject

After the above command sucessfully creates a new project, you can run the following command to browser into it.

cd helloproject

Now, you can open your newly created project in your favorite code editor, for our example, we will use Visual Studio Code

Django Project Directories

You should be able to see the following directories

Django Hello World Project Directories

HERE,

  • helloproject is a directory that has been created in our parent project directory that is also named helloproject

    • __init__.py this file is used to intialize a directory as a python package
    • asgi.py this file is used to expose the ASGI callable as a module-level variable called application.
    • settings.py this file contains project settings. We will explore it more as we proceed with the lessons
    • urls.py this file is used to define URLs that our web application users will be able to access from the web browser
    • wsgi.py this file is used as an interface between our python code and the web server. WSGI stands for Web Server Gateway Interface.
  • manage.pythis file is an administrative tool that we will use to automate common repetitive tasks such as running the built-in server, making and running migration files, starting the django shell in the commandline etc.

You can now run the following command in the terminal to start the built-in server

python3 manage.py runserver

HERE,

  • The above command starts the built-in server running at port 8000

Load the following URL into your browser

http://localhost:8000

You should be able to see the following Django default page

Django 3 Default Page

How to create an application in Django

An applictaion in Django is a specialized component that performs a specific task. For example, when you are working on an online store, you can create an app for the projects, another app for the shopping cart and another for checkingout etc. Applications allow us to separate our project into small manageable self contain components.

Run the following command to create an app called hello. Before running this commad, make sure you browser to the root of your project.

cd ~/repos/helloproject
django-admin startapp hello

HERE,

  • The first command browsers to the root of our project while the second command creates a new application using the startapp command. The new app is called hello.

Go back to the text editor and you should be able to see the following directory in the root with the following files inside hello directory.

Django Hello App Directories

HERE,

  • migrations this directory will contain all migration files that we will be creating. We will cover this in upcoming lessons.
  • __init__.py this file initializes the directory hello to a python package
  • admin.py this file is used to register application models so that they can appear in the admin panel app that comes built-in into Django
  • apps.py this file is used to register the application and run anycode that you might need when initialization the app. Most of the times, we will not make any changes to this file.
  • models.py this file is used to define models for our application. Models are classes that allow us to interact with the database. We will cover this more in future lessons
  • tests.py this file is used for tests.
  • views.py this file is used to define view functions and generic classes. Views are responsibe for receiving requests from the user, taking appropriate action and returning results via simple text, JSON or loading templates etc.

We will now use our hello applictaion to override the default Django page.

Open the file /helloproject/hello/views.py and replace its contents with the following

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def hello_index(request):
    html = "<h1>Hello World!</h1>"
    return HttpResponse(html)

HERE,

  • from django.http import HttpResponse imports the HttpResponse object from the package django.http.
  • def hello_index(request): defines a function hello_index that accepts a parameter request.
  • html = "<h1>Hello World!</h1>" defines a simple HTML H1 tag
  • return HttpResponse(html) returns an HttpResponse object that accepts the variable html as the parameter.

Now that we have defined a view function, we need to define a route for it that will be calling the above function.

Open the file /helloproject/helloproject/urls.py and add the following code

...
from hello.views import hello_index

HERE,

  • The above code imports the hello_index function from the views file in the package hello. Remember hello is the application that we created in our project.

Next we will define URL by adding the following entry to the list variable urlpatterns

path('', hello_index),

HERE,

  • path('', hello_index), the empty string is used to define the home page and call the function hello_index

The complete file for helloproject/helloproject/url.py should now be as follows

from django.contrib import admin
from django.urls import path
from hello.views import hello_index

urlpatterns = [
    path('', hello_index),
    path('admin/', admin.site.urls),
]

We are now ready to test our code

Start trhe built-in server by running the following command

python3 manage.py runserver

Load the following URL into your web browser

http://localhost:8000

The default homepage should disappear and you should be able to see the following page.

Django Hello World

 

The difference between a project and an application

A project refers to the system as a whole with the sole purpose of delivering the desired end result. For example, when working on an online store, the project is made up of all functionality from registration, shopping and checking out while an application refers to a single component within the complete system. An example of an application would be the customer registration component.

Applications make it easy for us to manage our project especially when it becomes large and complex.

Course Project KodeBlog Online Book Store

Now that we have covered the basics of Django, created a development environment and have created our first hello world application, we can now take on a more challenging project. We will create an online book store app. We will be able to create categories, authors, books and display the data in the application.

The user will be able to view category, author and book details. We will also have forms for editing the data in a secure way, develop a simple API for our online store and incoporate a shopping cart that will allow the visitors to our store to add items to the shopping cart.

Summary

Django applications are made up of a project which in turn is made up of a number of specialized applications. Views receive requests and take the necessary steps such as communicating with the database to retrieve data, and forward it to the template so that it can be formatted in a presentable way to the user who requested for it. The django-admin tool is used to create projects and apps etc. The file manage.py is used to automate repetitive tasks such as runserver, make and run migration files etc.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

Django Development Environment

Django Online Bookstore, Course Project

Leave A Reply