DEV Community

loading...
Cover image for ๐Ÿค– ๐Ÿ Create your first Django app: Hello world app
Developer Road

๐Ÿค– ๐Ÿ Create your first Django app: Hello world app

Daniel Diaz
Self-taught Python/Django Developer, Technical Writer, and long-life learner. I enjoy creating software from scratch and sharing knowledge with stunning technical articles.
Originally published at developerroad.herokuapp.com ใƒปUpdated on ใƒป11 min read

First of all! ๐Ÿ˜€

Take a good look at this article, that will give you a quick grasp of what is Django, and why you should use it!

What you will learn ๐Ÿ“–

Continuing with this article, here you will learn:

  • Install Django, (and it's dependencies)
  • Take a quick look at the Django Project structure.
  • The basics of the MVT pattern
  • Use the Django Template Language

Source code ๐Ÿ’ป

The source code of this tutorial is available in this Github repository:

GitHub logo Developer-road / django-hello-world

A simple Django hello world app

django-hello-world

A begginers hello world guide to the django web framework.

Install requirements:

python3 -venv .venv

source .venv/bin/activate


pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode



Installation ๐Ÿ

First of all, you have to install Python, which is one of the most loved languages in the world, and Django is built with it!

Check out the python downloads page

image

And install the Python 3 version for your operative system: Windows, Mac or Linux

Reminder: Most of Linux distributions, comes with Python Preinstalled so you don't have to worry about install it.

Terminal

Now it's time to use the terminal, or Command line interface ๐Ÿ˜จ . I know it can be scaring to use the terminal for the first time, but it is an essential skill, that I think every developer should have.

Depending in your operating system, you have different terminal emulators installed, so let's take a look of each terminal for Different OS.

Windows

In windows you have to preinstalled options, CMD and Powershell. Both are terrible ๐Ÿ˜‚, but you can get the job done with them.

Note: In windows the file structure is different from UNIX based (Mac OS and Linux), so usually I recommend to install Git bash, that lets you to run the same commands I'll be using in this tutorial, but I let it up to you.

Mac OS and Linux

In these operative systems, you have built in terminals and you can search it directly in your programs search bar.

In my case ๐Ÿ˜€
image

Also if you find too complex to use your system terminal, just use integrated terminals from different code editors

For example Vs Code

image

Verifying Python Installation

Now that you know to open up your terminal, let's check if we have Python installed

python --version
Enter fullscreen mode Exit fullscreen mode

If I run this command I get:

image

Which means that the Python version. I have installed in my system is Python 3.8.6.

Also check for pip

pip stands for PIP install packages. It is a Python package manager, that will allow us to install different useful packages, included Django ๐Ÿ˜†

To check if pip installed, we use

pip --version
Enter fullscreen mode Exit fullscreen mode

As you see, I have pip 20.3.3 installed
image

Installing Django

Before we can install Django, we should set up a virtual environment, to do that, we run

python -m .venv
Enter fullscreen mode Exit fullscreen mode

This will create a Virtual environment with the name of .venv.

If you want to know more about virtual environments, just take a look on this post.

Now activate that virtual environment ๐Ÿ˜€

source .venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

You can easily install Django, with a simple pip command

pip install django
Enter fullscreen mode Exit fullscreen mode

You will see something like this in your terminal

image

Lastly confirm your django installation

โ•ฐ(.venv)โ”€ฮป pip freeze                                                                                  0 (0.003s) < 21:15:55
asgiref==3.3.1
Django==3.1.7
pytz==2021.1
sqlparse==0.4.1
Enter fullscreen mode Exit fullscreen mode

As you see I installed Django 3.1.7, which is the latest version of Django, in this moment.

Advice: I always recommend to use the latest django version, since it has the more patches and security fixes.

But if you are already working with a team, or for a company with an older Django version, you should continue using it.

Anyways the Django project team, had been doing an amazing job, because no matter if you learn the Django 3.x version, 2.x or even 1.x (Don't use it please ๐Ÿ˜†), most of the core functionality still the same.

Creating a project

To create a project in django, you will use the following command

django-admin startproject helloworld
Enter fullscreen mode Exit fullscreen mode

This will create a folder name helloworld, and inside that folder, there will be another folder named hellowold, and a Python file manage.py

โ•ฐ(.venv)โ”€ฮป tree                                                                                        .
โ”œโ”€โ”€ helloworld
โ”‚   โ”œโ”€โ”€ helloworld
โ”‚   โ”‚   โ”œโ”€โ”€ asgi.py
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ settings.py
โ”‚   โ”‚   โ”œโ”€โ”€ urls.py
โ”‚   โ”‚   โ””โ”€โ”€ wsgi.py
โ”‚   โ””โ”€โ”€ manage.py

Enter fullscreen mode Exit fullscreen mode

I know this file structure could be confuse ๐Ÿ˜•, so I'll explain it in detail.

Django double folder structure

As you may notice, when you create a project in Django, there will be two folders named the same, but these two have differences.

The root folder /helloworld is just like a container, it doesn't matter for django, and it is only there for organization purposes.

You can rename it with whatever you want.

In the other hand there is the inside folder /helloworld/helloworld. It is a Python package since it has a __init__.py.

We will use it to configure our Django project, and to import everything from other apps. (Later we'll see what is an app ๐Ÿ˜‰).

Inside the helloworld package, we can found another important files:

  • __init__.py, indicates that the project folder must be considered as a package
  • settings.py, used to configure our app.
  • urls.py, lets you add or remove url patterns
  • wsgi.py & asgi.py, configure your deploy server

Finally the manage.py file, is a command line utility that let us interact with the Django framework.

Running a development server.

To run a local server, run the following command

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

You can specify a port for the server. So this time I'll use the port 8080, as an demonstration.

python manage.py runserver 8080
Enter fullscreen mode Exit fullscreen mode

Note: You will see warning about migrations, but don't worry you will not manage them in this tutorial.

After running that command, go to your browser and type:

# Or the port you used in the runserver command
localhost:8080
Enter fullscreen mode Exit fullscreen mode

After doing that, you should get a page like this, that confirms the installation

image

Ok, you got it. You installed your first Django project ๐Ÿฆ„

Now let's go with the interesting part ๐Ÿ˜

Using the MVT pattern

Before continue, I want to tell you about the MVT pattern or Model, View, Template. I know that it sounds confusing, but please don't turn off your brain ๐Ÿง , and don't give up ๐Ÿ‘.

MVT pattern

First of all, why Django uses this pattern? ๐Ÿ’ญ

Django uses this pattern, because it allows the developer, to skip the tedious part of creating a custom controller.

Now, let's get into the different parts of this design pattern:

  • Model: Holds all of the logical structure of your database. It manages all of the operations, in the database, like creating, updating and deleting.

image

Due to the models, we as Django Developers mustn't learn SQL ๐Ÿ’ฝ (although it would be a good plus).

  • View: As a quick definition, a view receives a request, and return a response. Usually the view receives a HTTP response, like GET, and return a html file, or a Json file, or nearly everything.

That return of html files, is called *Template *.

  • Template: Is what is shown to the user, if everything results Ok with his/her request. It acts as a presentation layer, and you can write them with html, css, javascript, and a special language: The Django template language.

image

These templates, are designed to "Don't repeat yourself", since Django uses a special language DTL, to build them.

Creating the hello world app

Since this is a beginners guide, we will only use, Urls, Views and templates ๐Ÿ˜‰.

Creating an app

Before continuing, we're going to create a django app.

django-admin startapp myapp
Enter fullscreen mode Exit fullscreen mode

Our app is called myapp, and it contains several files and a strange folder named migrations ๐Ÿ˜ฎ.

Let's take a look at the structure of our app.

. myapp/
โ”œโ”€โ”€ admin.py
โ”œโ”€โ”€ apps.py
โ”œโ”€โ”€ __init__.py
โ”œโ”€โ”€ migrations
โ”‚   โ””โ”€โ”€ __init__.py
โ”œโ”€โ”€ models.py
โ”œโ”€โ”€ tests.py
โ””โ”€โ”€ views.py

1 directory, 7 files
Enter fullscreen mode Exit fullscreen mode
  • admin.py : Here we can register our models in the admin page (We will see it in next articles)

  • tests.py : This file is where we make our unit tests.

  • models.py : Where we create our models, and where we interact with our database

  • apps.py : Configuration of our app. I've never touch it ๐Ÿ˜…

  • views.py : All of our business logic lives here. This file contains the views that will render our templates.

  • /migrations : Here is where migrations live. I'll create a post about it, but as a quick concept a migration is a recording of the changes of our models.

Differences app and a Project

Do you remember that we already created a project, called helloworld ?.

Well now we just created an app, and here are the differences.

Project App
Collections of apps, for a website Web application that does something
Can contain multiple apps Can be in multiple projects
Ex: A Blog website Ex: A comments app that can be in many projects, like Disqus

Until now, we haven't touched any code, so let's get into it.

Hands on ๐Ÿ™Œ

Installing our app:

We just created an app, so let's install it in the settings.py file

# helloworld/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Custom apps
    'myapp',
]
Enter fullscreen mode Exit fullscreen mode

After installed our new app, we can get into url patterns.
Go to the urls.py file, in our project folder and modify the following things.

from django.urls import path, include

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

    # The url path of our new app
    path('', include('myapp.urls')),
]
Enter fullscreen mode Exit fullscreen mode

Here we imported the function include, that as the name suggests include the url patterns of external apps ๐Ÿ˜€.

Then we created another path, with the destination of '', that means that when a user hits the url, without any other pattern, we call the urls of the app myapp

As you may noticed, we are calling the urls as a Python package, so myapp.urls means:

  1. Go to the myapp package
  2. Extract the url patterns of the urls.py file.

But you would say me: Daniel! are you crazy ๐Ÿคฏ, that file hasn't been created.

And yeah, you are right. So we need to create it manually.

You can create it from your code editor, or from your terminal

cd myapp/

touch urls.py
Enter fullscreen mode Exit fullscreen mode

After creating that file, we are going to made the fun stuff! ๐Ÿ˜

Creating our first view:

Let's edit our views.py file.


from django.http import HttpResponse

# Create your views here.


def helloworldview(request):

    response = "Hello world, this is my first Django app! :)"


    return HttpResponse(response)
Enter fullscreen mode Exit fullscreen mode

Here we imported the HttpResponse class and we passed a variable response, with a value of: "Hello world .."

Ok cool, but next we have to create an url for that view, let's go to the myapp/urls.py file.

from django.urls import path

from .views import helloworldview

urlpatterns = [
    path("", helloworld),
]
Enter fullscreen mode Exit fullscreen mode

As in the urls.py of the project folder, we imported path, and created url patterns for our app. Also we used a new concept, we passed a view to our path function.

All of the stuff we just do, means that each time that we hit localhost:8000, we request the url pattern of "".

That url will call our view function named helloworldview, that takes our request, and returns a HttpResponse, with the content of "Hello world".

Not that hard to understand, right ๐Ÿ˜…?

Now run the server, and watch your first app working!

python manage.py runserver

# See it on localhost:8000
Enter fullscreen mode Exit fullscreen mode

image

Using Django templates

The last part of this tutorial will be about, Templates in Django ๐Ÿ˜€

First of all a Django template, is a html document, that uses the Django template language, to incorporate data and logic on our front end.

Your first template in Django

Before using templates, we need to create a folder in our app to be able to use it.

So let's create one:

cd myapp/

mkdir templates
Enter fullscreen mode Exit fullscreen mode

You just created a directory, named templates. That tells Django to search for templates in that folder.

Create a file, named index.html, that will be our first template.

touch index.html
Enter fullscreen mode Exit fullscreen mode

Now, paste the following html, in the template.

<h1>Hello world, this is my first template</h1>

<p>This is a cool html paragraph!</p>
Enter fullscreen mode Exit fullscreen mode

After that we are going to modify the helloworldview, in order to render our template

from django.shortcuts import render

def helloworldview(request):

    template = "index.html"

    context = {}    

    return render(request, template, context)
Enter fullscreen mode Exit fullscreen mode

Here, we used the function render, that takes as parameters, the user request, the name of the template, in this case index.html, and the context, that we will see how to use it later.

After that minor changes, you'll see something like this.

image

Using the DTL

Now we will see the basics of Django template language.

Create a file base.html, inside the templates folder.

touch base.html
Enter fullscreen mode Exit fullscreen mode

There we will paste the basic structure of a html Document.

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Django Hello world</title>
    </head>

    <body>
        {% block body %}


        {% endblock body %}


    </body>

</html>
Enter fullscreen mode Exit fullscreen mode

But with a little change we are using DTL tags. Those are of the shape {% tag %}. The tag we used in this case, is:

{% block [name of the block] %}


{% endblock [name of the block] %}
Enter fullscreen mode Exit fullscreen mode

That tags, allow us to put html code, in block codes, as we are going to see now.

Template inheritance ๐Ÿ˜

Now modify, the index.html file.

{% extends 'base.html' %}

{% block body %}
<h1>Hello world, this is my first template</h1>

<p>This is a cool html paragraph!</p>


{% endblock body %}
Enter fullscreen mode Exit fullscreen mode

Here we just do a strange thing! ๐Ÿคฏ, we used template inheritance, and DTL blocks.

base

You call, the inheritance with the tag {% extends "name of template" %}

And with the block tag you replace the content inside the block

{% block [name of block] %}
... Replaced content

{% endblock [name of block] %}

Enter fullscreen mode Exit fullscreen mode

If we look at the source page of our page, we get something like this.

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Django Hello world</title>
    </head>

    <body>

<h1>Hello world, this is my first template</h1>

<p>This is a cool html paragraph!</p>



    </body>

</html>
Enter fullscreen mode Exit fullscreen mode

Context variables and for loops

We are going to pass context variables from our views. so let's modify the view

def helloworldview(request):

    template = "index.html"

    people = ["daniel", "nicolas", "tom", "henry"]

    context = {"people": people}    

    return render(request, template, context)
Enter fullscreen mode Exit fullscreen mode

We are passing, a context dictionary to our template. Our key "people" is a list of strings.

Now we are going to make a for loop, to iterate through that list ๐Ÿ˜.

{% extends 'base.html' %}

{% block body %}
<h1>Hello world, this is my first template</h1>

<p>This is a cool html paragraph!</p>


{% for person in people %}
    <p>{{person}}</p>
{% endfor %}


{% endblock body %}
Enter fullscreen mode Exit fullscreen mode

As you may notice, the for loops in DTL are exactly the same as they are in Python.

And variables, in DTL are represented with {{ name_variable }}

If we check our server, we'll get something like
this. ๐Ÿคฏ

image

Amazing, it isn't ?

Conclusion:

In this tutorial, you learned the basics of django.

From creating function based views, to building url patterns and using the Django template language ๐Ÿ˜ƒ.

Any questions or doubts ? Let me know in the comments

Follow me in My blog,
to get more awesome tutorials like this one.
Please consider supporting me on Ko-fi you help me a lot to
continue building this tutorials!.
ko-fi

Discussion (1)

Collapse
danidiaztech profile image
Daniel Diaz Author

Any question? Let me know!