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
How to create a new project in Django
In this section, we will learn how to create a new project using the
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
- The above command installs django in our virtual environment
The sytanx for starting a new project is as follows
django-admin startproject projectname
django-admin startproject projectnameuses the utility
django-adminto run the command
startprojectwhich creates a new project called
You can now run the following command to create a new project called
django-admin startproject helloproject
After the above command sucessfully creates a new project, you can run the following command to browser into it.
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
helloprojectis a directory that has been created in our parent project directory that is also named
__init__.pythis file is used to intialize a directory as a python package
asgi.pythis file is used to expose the ASGI callable as a module-level variable called
settings.pythis file contains project settings. We will explore it more as we proceed with the lessons
urls.pythis file is used to define URLs that our web application users will be able to access from the web browser
wsgi.pythis file is used as an interface between our python code and the web server.
WSGIstands 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
- The above command starts the built-in server running at port
Load the following URL into your browser
You should be able to see the following Django 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
- The first command browsers to the root of our project while the second command creates a new application using the
startappcommand. The new app is called
Go back to the text editor and you should be able to see the following directory in the root with the following files inside
migrationsthis directory will contain all migration files that we will be creating. We will cover this in upcoming lessons.
__init__.pythis file initializes the directory
helloto a python package
admin.pythis file is used to register application models so that they can appear in the admin panel app that comes built-in into Django
apps.pythis 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.pythis 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.pythis file is used for tests.
views.pythis 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)
from django.http import HttpResponseimports the
HttpResponseobject from the package
def hello_index(request):defines a function
hello_indexthat accepts a parameter
html = "<h1>Hello World!</h1>"defines a simple HTML H1 tag
return HttpResponse(html)returns an
HttpResponseobject that accepts the variable
htmlas 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
- The above code imports the
hello_indexfunction from the
viewsfile in the package
hellois the application that we created in our project.
Next we will define URL by adding the following entry to the list variable
path('', hello_index),the empty string is used to define the home page and call the function
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
The default homepage should disappear and you should be able to see the following page.
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.
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.