How to build a Django App - Part 4: Creating the front-end

5 min read ⋅ 137 views

Now that we know our back-end is working, we can turn our attention to the front-end. Currently localhost:8000/todos/ gives us a page with nothing but a piece of text. So, let’s begin by heading back to the file containing the code for that piece of text. Navigate to the views.py file and then to the return statement. We are going to edit the return statement so that it returns a .html file. Replace HttpResponse(‘your text’) with render(request, index.html). The file should now contain the following code.

from django.shortcuts import render

from django.http import HttpResponse


def index(request):

return render(request, ‘index.html’)

render combines a given template (index.html in this case) with a given context dictionary (request) and returns a HttpResponse object with that rendered text.

Now that we have done that we need to create the index.html file. Create a new folder inside todos called templates. Then, inside this folder, we can create our index.html file. For now, just type HELLO FROM INDEX or something similar inside this file and hit save.

Now, when you refresh the page, it will now say HELLO FROM INDEX. This tells us that our HTML file is correctly being displayed. Now, if we want to pass in variables, we can do so by adding an object as the third parameter to our return statement.

What we are going to do is create a query to get our todos. In order to do this, the first thing we need to do is import our model into our views.py file. Add the following import statement to views.py.

from .models import Todo

Then, inside the index function, type the following code.

todos = Todo.objects.all()[:10]

[:10] defines how many of them we want.

Now we want to pass the above into our template. To do this we need to create another variable called context and assign it the following code.

context = {

‘Todos’ :todos

}

The code for this file should now look like this.

from django.shortcuts import render

from django.http import HttpResponse

from .models import Todo


def index(request):

todos = Todo.objects.all()[:10]

context = {

'todos' :todos

}

return render(request, 'index.html', context)

Notice that context has been passed into our return statement. Without this, our to-dos will not be displayed.

Now we want to go back to our HTML file. We need this file to loop through our to-dos. Delete all the code from this file and then add the following.

<ul>

{% for todo in todos %}

<li>{{todo.title}}: {{todo.text}}</li>

{% endfor %}

</ul>

This code is going to display our todos in a list format. Feel free to experiment with HTML and CSS yourself but as this is a Python tutorial we won’t be focusing too much on the markup or the design.

Save the file and then refresh the webpage once again. It should now look something like this.

Now that we know this is all working, we should go and add our HTML tags to the file, again we won’t be going into detail on the HTML markup, but it is still important that the file contains the correct syntax. Add the following code to your HTML file so that it is marked up correctly.

<!DOCTYPE html>

<html lang="en" dir="ltr">

<head>

<meta charset="utf-8">

<title></title>

</head>

<body>

<ul>

{% for todo in todos %}

<li>{{todo.title}}: {{todo.text}}</li>

{% endfor %}

</ul>

</body>

</html>

You can then include a header by adding the following code in between the first body tag and the first ul tag, like this. 

<header>

<h1>To-Do List</h1>

<hr>

</header>

Now, we should add a details page to each of our todos. To do this, we need to wrap out todo.title in a link. Edit the code inside the li tags so that it matches the following.

<li><a href="/todos/details/{{todo.id}}">{{todo.title}}</a>: {{todo.text}}</li>

Now, if we refresh our webpage, we can click on each todo. If you click on the first one, you will see in the address bar that it has gone to /details/1. If you click on the second one, it will go to /details/2. You will also notice, however, that the pages are displaying a (404) error as the page can’t be found.

So now, let’s make those links actually work correctly. Navigate back to the urls.py file inside the “todos” folder. Inside this file, we are going to create a new route. To do this, we need to add the following code to our url patterns variable.

re_path(r'^details/(?P<id>\w{0,50})/$', views.details)

The code for the file should now look like this.

from django.urls import re_path

from . import views


urlpatterns = [

re_path(r'^$', views.index, name='index'),

re_path(r'^details/(?P<id>\w{0,50})/$', views.details)

]

(?P<id>\w{0,50}) is the code that is needed if you want it to accept an id parameter. So now, let’s save that and go back to views.py. Here, we are going to create a new function called “details”. This function is going to need to be passed a request as well as an id. This is necessary because of how we set the route. Enter the following code to create the details function.

def details(request, id):

todo = Todo.objects.get(id=id)

context = {

'todo' :todo

}

return render(request, 'details.html', context)

This function takes a single to-do and then returns a details page for that to-do. Now that we’ve done that we need to create the details.html file. Go ahead and create this file inside of the templates folder, like we did with the index.html file.

Inside this file, enter the following code.

<h1>{{todo.title}}</h1>

Now, if we go back to localhost:8000/todos and click on “Todo One”, we should get a page like this.

We can see from this that our details page is working correctly and displaying the title of the to-do. Now at the moment, our details page is pretty bare so let’s add our text to it. We can do this using the same method as before, but this time we want to use a paragraph tag and bring in todo.text. Add the following code to the details.html file.

<p>{{todo.text}}</p>

We also want this page to display the date and time that the todo was created. To include those, add the following code to the file.

<br>

Created on {{todo.created_at}}

This code first adds a line break to the page and then brings in the date and time, as requested.

Now, if we save that file and refresh the page, we should see that our text, date and time for that to-do have been added, like so.

Finishing our Django app

The next article is the final part of this tutorial. It will show you how to organise your HTML pages by using “partials” as well as how to add a form to the front-end, allowing users to enter To-dos themselves, without needing access to the admin panel. 

See you in part five!


To skip to a specific article in this series, you can use the following links.

Part 1: What is Django?

Part 2: Setting up the server

Part 3: Creating the database

Part 5: Finishing the Django App



Python



MORE ARTICLES

How To Structure a Python Project

Writing programs isn’t all about the code. Sure when it comes down to it, the code is what makes the functioning program...

6634 views

Pipenv - First Impressions

Pipenv is an experimental tool with the purpose of bringing together different packaging tools in one place. It has been...

4003 views

How To Write Tests For Python

An important part of development in any Python project is testing. Testing is used to help define the intent of your cod...

2998 views