Codementor Events

Building an Hello World Application with Python/Django

Published Jun 21, 2017Last updated Dec 17, 2017
Building an Hello World Application with Python/Django

I have created this post to make it easy for beginners to get started with using Django to build a web project. Django is a python web framework widely known for its simplicity, and it provides so many extra functionalities not offered by other frameworks. According to Wikipedia, Django eases the creation of complex, database-driven websites. It also emphasizes reusability and pluggability of components, rapid developments, and the principle of DRY (Don’t Repeat Yourself).

To get started with Django, you need to have Python installed and Virtual Environment setup. If you don’t, check out these links (Python and virtualend) for instructions.

The next steps will walk us through creating an actual Django project.

1. Creating a virtual environment — We need to create a virtual environment where we will install all our dependencies. To do this, we run:

mkvirtualenv my_project # Make a new virtual environment named my_project

Note: You can change the name of the project to whatever you like

Your virtual environment may not be activated by default. To activate it, run:

workon my_project # Activate the my_project virtual environment

2. Installing dependencies — Since we have created and activated our virtual environment, we need to install the dependencies for our project. To do this, we run the following command:

pip install django # This would install the django package to the virtual environment

3. Get into a working directory. You might need to create a directory and cd into the directory like so:

mkdir my_django_project # Create my_django_project directory
cd my_django_project # Change working directory into my_django_project directory

4. Once you are in your working directory, you will need to create a new Django project by using the Django package we installed in Step 3. To do that, run the following command:

django-admin startproject helloworld_project # Create a new project named helloworld_project

If successful, you should see a new folder, helloworld_project, added to your working directory.

Your new folder structure should look similar to this:

└── helloworld_project
    ├── helloworld_project
    │   ├── __init__.py
    │   ├── settings.py
    │   ├── urls.py
    │   └── wsgi.py
    └── manage.py

This means that there is an outer helloworld_project folder containing the manage.py file as well as an inner helloworld_project folder. The inner folder contains the project basic setup files like the urls for your app, settings, and the app configurations.

5. Next, we cd into the outer helloworld_project folder and run the following command:

python manage.py runserver # Run the django server

If successful, you should something similar to this:

Performing system checks...
System check identified no issues (0 silenced).
You have 13 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
June 17, 2017 - 12:22:32
Django version 1.11.2, using settings 'helloworld_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

To suppress the unapplied migration warning, stop the server with CONTROL-C and run the command

python manage.py migrate

Next, visit the server at http://127.0.0.1:8000/ on your favorite browser. You should see a page similar to this:

Screen Shot 2017-06-17 at 1.27.56 PM.png

6. The next thing is to create an app in our Django project. This is where we will design and render our Hello World page. So, let’s create a new app called my_app (or whichever name you prefer). Before creating the app, ensure you are in the outer hello_world project where you have the manage.py file. To create the app, we run this command:

django-admin startapp my_app # Create a new django app named my_app
or
python manage.py startapp my_app # Create a new django app named my_app

If the above is successful, the directory structure for the outer hello_world folder should look similar to this:

├── db.sqlite3
├── helloworld_project
│   ├── __init__.py
│   ├── __init__.pyc
│   ├── settings.py
│   ├── settings.pyc
│   ├── urls.py
│   ├── urls.pyc
│   ├── wsgi.py
│   └── wsgi.pyc
├── manage.py
└── my_app
    ├── __init__.py
    ├── admin.py
    ├── apps.py
    ├── migrations
    │   └── __init__.py
    ├── models.py
    ├── tests.py
    └── views.py

Before moving on, we need to add the new app we created to the list of installed apps in our settings file so that Django knows about it and can refer to it. To do that, open helloworld_project/settings.py file in a text editor and add my_app to the INSTALLED_APPS list.
For instance, if the initial value for the INSTALLED_APPS was:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

After adding the my_app app, it should look similar to this:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'my_app',
]

7. Next, we need to create a templates folder in our app directory. This is where our template files (html files) will live. Before creating the templates folder, ensure you are located inside the my_app directory. To achieve this, follow these steps (from inside the outer hello_world project folder):

cd my_app # Change directory into the new my_app directory
mkdir templates # Make a new directory named templates

8. After making the templates folder, we then create a new html file named index.html. This is where our html code will live. This can be achieved by entering the next set of commands:

cd templates # Change directory into the templates directory
touch index.html # Create a new index.html file

Next, open the index.html file with any text editor and paste in the following content:

<html>
<head><title>Home Page</title></head>
<body>
Hello world
</body>
</html>

9. The next thing is to set up our route/view to display our newly created html page. To do this, enter this command from the templates directory:

cd .. # Get out of the templates directory into my_app directory

When inside my_app directory, open the views.py file with your favorite text editor and paste in the following code snippet:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.views.generic import TemplateView
class HomeView(TemplateView):
    template_name = 'index.html'

The above is what is known as a Django view. A view determines what would be displayed to the user at a given route. In this case, we are telling Django to create a new view that renders the html file we created initially. But we haven’t told Django to use this view for any route, so Django doesn’t know when to use the view. The next thing we have to do is to set up a route to map to this view. That could be the index route, home route ( ‘/home’), etc.

To map our route to our view, we need to edit our urls.py file located in the inner hello_world project. To get to the folder containing the urls.py file from the current folder (my_app), type the following command:

cd .. # Get out from my_app folder into the outer helloworld_project folder
cd helloworld_project # Change directory into the inner helloworld_project folder

10. Next, we will open the urls.py file with our favorite text editor. We should see something similar to this:

"""helloworld_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

Next, we modify the urls.py file such that it looks like this:

"""helloworld_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from my_app.views import HomeView
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', HomeView.as_view()),
]

Note that we just added these two lines:

from my_app.views import HomeView # Import the new view we created
url(r'^$', HomeView.as_view()) # Map the HomeView to the index route

Next, we get out of the current folder (inner helloworld_project folder) to the outer helloworld_project and run the server again (if it is no longer running). To run the server, we need this command:

cd .. # Get into the outer helloworld_project directory
python manage.py runserver # Rerun the server

You should see a Hello World page similar to this:
Screen Shot 2017-06-17 at 3.09.07 PM.png

And your app is up and running! If you have any other questions, please comment below!

Discover and read more posts from Usman Ibrahim
get started
post comments6Replies
Free vote
a year ago

Utilizing a research paper writing service significantly enhanced my college experience. The best essay service I enlisted provided a harmonious blend of affordability and top-notch quality. This custom paper writing service surpassed my expectations, offering a tailored approach that met my academic needs without straining my budget. For those seeking a dependable and cost-effective solution, I wholeheartedly recommend this do my paper service—a reliable ally in navigating the challenges of academic writing.

Free vote
a year ago

I can’t emphasize enough how valuable the dissertation proposal writing services from this provider have been to me. As I embarked on the journey of crafting a compelling proposal, their team’s expertise and dedication shone brightly. They not only understood the nuances of a well-structured proposal but also took the time to grasp the specifics of my phd research proposal help. The result was a meticulously prepared document that surpassed my expectations. Thanks to their assistance, I now have a solid foundation for my dissertation that sets the stage for success. If you’re in need of professional support for your dissertation proposal, I wholeheartedly recommend their services

Hari Prasad
6 years ago

I got an error (NameError: name ‘from__future_import__unicode_literals’ is not defined)
how to solve it.

Show more replies