Create hello world in django?

In this article we’ll create the hello world app.

If you do not have Django installed, see the previous tutorials.

Django Web Developer Course

Make a new project

Execute these commands:

django-admin startproject first_django_project
cd first_django_project/
python manage.py startapp hello

Wait.. what did we just do?

  • We created a project named first_django_project
  • We created an app named hello
    Django projects can have multiple apps. Every app is like a website component, it has unique functionality.

Hello world code

We create the hello world code.
If you open the folder /first_django_project/hello you’ll see this:

django app

A lot of code! Which file do we need to change?

There’s one file named views.py

If you open the file you’ll see this:

from django.shortcuts import render

# Create your views here.

We’re gonna create our view in here.

Note: A view returns what the visitor sees: a webpage.

We’ll use HTML and a class to create the view.

If you are not familiar with these, I recommend this course:

Add these lines of code:
abstract-base-classes.md

from django.shortcuts import render

# Create your views here.

import textwrap

from django.http import HttpResponse
from django.views.generic.base import View

class HomePageView(View):

def dispatch(request, *args, **kwargs):
response_text = textwrap.dedent('''\
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello world</h1>
<p>Hello, world! Hola Mundo!</p>
</body>
</html>
''')
return HttpResponse(response_text)

We create a class HomePageView with the method dispatch.
This methods return the webpage code (in HTML).

URL router

Python needs to return the view, if we visit the webpage.

If we visit a webpage, the web browser sends a HTTP request.
To link views with the HTTP request, we create a new route.

In the app directory, create the file hello/urls.py with this content:

  
from django.conf.urls import url
from hello.views import HomePageView

urlpatterns = [
url(r'^$', HomePageView.as_view(), name='home'),
]

In the project directory, change /first_django_project/urls.py:

  
from django.conf.urls import include, url

urlpatterns = [
url(r'', include('hello.urls')),
]

Change app settings

Then we edit first_django_project/settings.py. Apps can be added or removed in this file.
You’ll see a list definition:

  
INSTALLED_APPS = [ .. ]


Add our hello app to this list.

We’ll remove the line SessionAuthenticationMiddleware.
Finally we’ll disable the database. This is defined somewhere on line 72.

  
DATABASES = {
...
}


Remove those lines.

All set!

Run the command:


python manage.py runserver

Then open the URL to see the result:

django hello world

If you see the above result, you completed this lesson!