ToDo App in Django Part 3: URLs, View, and Template in Django

Hello awesome people, welcome to the Learn Django by Doing Projects Series. In the previous tutorial, we saw about the Django model and the Django admin site. Also, we created the model Task for our todolist app to store data.

Today we’ll see about Django URLs, Django Views and Django Template for our todo app. Before this activate your virtual environment in your project directory path.

Creating Simple View

A Django view is just a Python function that receives a web request and returns a web response. All the logic to return the desired response goes inside the view.

Here we see simple Http Response example by returning it in web.

Open views.py of todolist app and add following lines.

from django.shortcuts import render, HttpResponse

# Create your views here.

def index(request):
    return HttpResponse("Hello World!!")

Adding URL patterns for your views

URL patterns allow you to map URLs to views. A URL pattern is composed of a string pattern, a view, and, optionally, a name that allows you to name the URL project-wide.

Django runs through each URL pattern and stops at the first one that matches the requested URL. Then, Django imports the view of the matching URL pattern and executes it, passing an instance of the HttpRequest class and the keyword or positional arguments.

Create a urls.py file in the directory of the todolist app and add the following
lines to it:

from django.urls import path
from . import views

urlpatterns = [
    path(' ',views.index,name="index")
]

Next, you have to include the URL patterns of the blog application in the main URL patterns of the project.

Edit the urls.py file located in the todoapp directory of your project and make it look like the following:

from django.contrib import admin
from django.urls import path,include # import include

urlpatterns = [
    path('admin/', admin.site.urls),
    path(' ',include('todolist.urls'))  # add this line
]

The new URL pattern defined with include refers to the URL patterns defined in the todolist application so that they are included under the / path.

Now just start development server using python3 manage.py runserver and open http://127.0.0.1:8000/ in your browser. And you get this:

returning http response todo app in django

Congrats!!

Creating templates for your views

We returned the HTTP response using the above codes but we can’t return text like above right? We have to return HTML pages to make an amazing website.

You have created views and URL patterns for the todolist application. URL patterns map URLs to views, and views decide which data gets returned to the user.

Templates define how the data is displayed; they are usually written in HTML in combination with the Django template language.

Now create templates directory in root directory. Project structure looks like this.

templates directory templates in django

templates directory, todoapp is main project directory, and todolist our app okay.

Make index.html file inside templates directory and add following lines:

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Todo App</title>
</head>

<body>
    <h1>Hello World!!</h1>
</body>

</html>

Before running this on the browser we’ll be adding a full path to the templates directory that’ll be holding all our HTML templates.

Open settings.py and then add “templates” in the TEMPLATES list like the below code:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ["templates"], # add this
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

The code above helps to prepare our template path. The BACKEND is the templating system you’d like to use and DjangoTemplate is the default.

Now open views.py of your todolist app and replace HttpResponse by following line:

from django.shortcuts import render, HttpResponse

# Create your views here.

def index(request):
    # return HttpResponse("Hello World!!")
    return render(request, "index.html") # add this line

Finally, you use the render() shortcut provided by Django to render the index page given template.

This function takes the request object, the template path, and the context variables to render the given template (we will see later about context variable). It returns an HttpResponse object with the rendered text (normally HTML code).

Now open the browser and refresh the page and yes make sure your development server is running. And you get this.

Now HTML page is rendered.

Adding Bootstrap

Now we are adding bootstrap to make the HTML page more amazing. Just go to the getboostrap doc and copy the Starter template and add code in index.html like following:

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

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css"
        integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">

    <title>Todo App</title>
</head>

<body>
    <div class="container">
        <h1>Hello, world!</h1>
    </div>
    <!-- Optional JavaScript -->
    <!-- Popper.js first, then Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
        integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js"
        integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/"
        crossorigin="anonymous"></script>
</body>

</html>

We put <h1>Hello, world!</h1> insde <div class="container">...</div>. container is just a bootstrap class.

Now again open your web browser and refresh the page.

bootstrap added in django

Reusing the code

Imagine, in our templates directory we have about.html, contact.html, and more HTML files. So, for the styling purpose, we need to copy the bootstrap file in every file. That doesn’t make sense.

To solve this problem we put the common code in base.html file. Now make base.html in templates directory and add the following lines like this in base.html.

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

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css"
        integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">

    <title>
        {% block title %}
        
        {% endblock title %}
        Todo App
    </title>
</head>

<body>
    <div class="container">
        {% block content %}

        {% endblock content %}
    </div>
    <!-- Optional JavaScript -->
    <!-- Popper.js first, then Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"
        integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js"
        integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/"
        crossorigin="anonymous"></script>
</body>

</html>

The base.html file will include the main HTML structure of the website and divide the content into the main content area and a sidebar.

You can see that there are two {% block %} tags. These tell Django that you want to define a block in that area. Templates that inherit from this template can fill in the blocks with content. You have defined a block called title and a block called content.

Now all other files will extend the base.html file to render common content like bootstrap.

Now we extend base.html in our index.html

{% extends 'base.html' %}

{% block title %}
Tasks - 
{% endblock title %}

{% block content %}
    <h1>Hello, world!</h1>
{% endblock content %}

With the {% extends %} template tag, you tell Django to inherit from the base.html template. Then, you fill the title and content blocks of the base template with content.

Open your browser and you can see everything is fine.

That’s it. I hope you enjoying this tutorial series. Please share with your friends, it’s help me lot.

Previous:

Next: