Reader small image

You're reading from  Web Development with Django

Product typeBook
Published inFeb 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781839212505
Edition1st Edition
Languages
Tools
Right arrow
Authors (5):
Ben Shaw
Ben Shaw
author image
Ben Shaw

Ben Shaw is a software engineer based in Auckland, New Zealand. He has worked as a developer for over 14 years and has been building websites with Django since 2007. In that time, his experience has helped many different types of companies, ranging in size from start-ups to large enterprises. He is also interested in machine learning, data science, automating deployments, and DevOps. When not programming, Ben enjoys outdoor sports and spending time with his partner and son.
Read more about Ben Shaw

Saurabh Badhwar
Saurabh Badhwar
author image
Saurabh Badhwar

Saurabh Badhwar is an infrastructure engineer who works on building tools and frameworks that enhance developer productivity. A major part of his work involves using Python to develop services that scale to thousands of concurrent users. He is currently employed at LinkedIn and works on infrastructure performance tools and services.
Read more about Saurabh Badhwar

Andrew Bird
Andrew Bird
author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

Bharath Chandra K S
Bharath Chandra K S
author image
Bharath Chandra K S

Bharath Chandra K S lives in Sydney, Australia, and has over 14 years of software industry experience. He is very passionate about software development on the Python stack, including frameworks such as Flask and Django. He has experience working with both monolithic and microservice architectures and has built various public-facing applications and data processing backend systems. When not cooking up software applications, he likes to cook some nice food.
Read more about Bharath Chandra K S

Chris Guest
Chris Guest
author image
Chris Guest

Chris Guest is based in Melbourne and started programming in Python 24 years ago, when it was an obscure academic language. He has since used his Python knowledge in the publishing, hospitality, medical, academic and financial sectors. Throughout his career, he has worked with many Python web development frameworks, including Zope, TurboGears, web2py, and Flask, although he still prefers Django.
Read more about Chris Guest

View More author details
Right arrow

3. URL Mapping, Views, and Templates

Overview

This chapter introduces you to three core concepts of Django: views, templates, and URL mapping. You will start by exploring the two main types of views in Django: function-based views and class-based views. Next, you will learn the basics of Django template language and template inheritance. Using these concepts, you will create a page to display the list of all the books in the Bookr application. You will also create another page to display the details, review comments, and ratings of books.

Introduction

In the previous chapter, we were introduced to databases, and we learned how to store, retrieve, update, and delete records from a database. We also learned how to create Django models and apply database migrations.

However, these database operations alone cannot display the application's data to a user. We need a way to display all the stored information in a meaningful way to the user; for example, displaying all the books present in our Bookr application's database, in a browser, in a presentable format. This is where Django views, templates, and URL mapping come into play. Views are the part of a Django application that takes in a web request and provides a web response. For example, a web request could be a user trying to view a website by entering the website address, and a web response could be the web site's home page loading in the user's browser. Views are one of the most important parts of a Django application, where the application logic...

Function-Based Views

As the name implies, function-based views are implemented as Python functions. To understand how they work, consider the following snippet, which shows a simple view function named home_page:

from django.http import HttpResponse
def home_page(request):
    message = "<html><h1>Welcome to my Website</h1></html>"
    return HttpResponse(message)

The view function defined here, named home_page, takes a request object as an argument and returns an HttpResponse object having the Welcome to my Website message. The advantage of using function-based views is that, since they are implemented as simple Python functions, they are easier to learn and also easily readable for other programmers. The major disadvantage of function-based views is that the code cannot be re-used and made as concise as class-based views for generic use cases.

Class-Based Views

As the name implies, class-based views are implemented as Python classes. Using the principles of class inheritance, these classes are implemented as subclasses of Django's generic view classes. Unlike function-based views, where all the view logic is expressed explicitly in a function, Django's generic view classes come with various pre-built properties and methods that can provide shortcuts to writing clean, reusable views. This property comes in handy quite often during web development; for example, developers often need to render an HTML page without needing any data inserted from the database, or any customization specific to the user. In this case, it is possible to simply inherit from Django's TemplateView, and specify the path of the HTML file. The following is an example of a class-based view that can display the same message as in the function-based view example:

from django.views.generic import TemplateView
class HomePage(TemplateView...

URL Configuration

Django views cannot work on their own in a web application. When a web request is made to the application, Django's URL configuration takes care of routing the request to the appropriate view function to process the request. A typical URL configuration in the urls.py file in Django looks like this:

from . import views
urlpatterns = [path('url-path/' views.my_view, name='my-view'),]

Here, urlpatterns is the variable defining the list of URL paths, and 'url-path/' defines the path to match.

views.my_view is the view function to invoke when there is a URL match, and name='my-view' is the name of the view function used to refer to the view. There may be a situation wherein, elsewhere in the application, we want to get the URL of this view. We wouldn't want to hardcode the value, as it would then have to be specified twice in the codebase. Instead, we can access the URL by using the name of the view, as follows...

Templates

In Exercise 3.01, Implementing a Simple Function-Based View, we saw how to create a view, do the URL mapping, and display a message in the browser. But if you recall, we hardcoded the HTML message Welcome to Bookr! in the view function itself and returned an HttpResponse object, as follows:

message = f"<html><h1>Welcome to Bookr!</h1> "\
"<p>{Book.objects.count()} books and counting!</p></html>"
return HttpResponse(message)

Hardcoding of HTML inside Python modules is not a good practice, because as the content to be rendered in a web page increases, so does the amount of HTML code we need to write for it. Having a lot of HTML code among Python code can make the code hard to read and maintain in the long run.

For this reason, Django templates provide us with a better way to write and manage HTML templates. Django's templates not only work with static HTML content but also dynamic HTML templates.

Django...

Django Template Language

Django templates not only return static HTML templates but can also add dynamic application data while generating the templates. Along with data, we can also include some programmatic elements in the templates. All of these put together form the basics of Django's template language. This section looks at some of the basic parts of the Django template language.

Template Variables

A template variable is represented in between two curly braces, as shown here:

{{ variable }}

When this is present in the template, the value carried by the variables will be replaced in the template. Template variables help in adding the application's data into the templates:

template_variable = "I am a template variable."
<body>
        {{ template_variable }}
    </body>

Template Tags

A tag is similar to a programmatic control flow, such as an if condition or a for loop...

Summary

This chapter covered the core infrastructure required to handle an HTTP request to our website. The request is first mapped via URL patterns to an appropriate view. Parameters from the URL are also passed into the view to specify the object displayed on the page. The view is responsible for compiling any necessary information to display on the website, and then passes this dictionary through to a template that renders the information as HTML code that can be returned as a response to the user. We covered both class- and function-based views and learned about the Django template language and template inheritance. We created two new pages for the book review application, one displaying all the books present and the other being the book details view page. In the next chapter, we will learn about Django admin and superuser, registering models, and performing CRUD operations using the admin site.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Web Development with Django
Published in: Feb 2021Publisher: PacktISBN-13: 9781839212505
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Authors (5)

author image
Ben Shaw

Ben Shaw is a software engineer based in Auckland, New Zealand. He has worked as a developer for over 14 years and has been building websites with Django since 2007. In that time, his experience has helped many different types of companies, ranging in size from start-ups to large enterprises. He is also interested in machine learning, data science, automating deployments, and DevOps. When not programming, Ben enjoys outdoor sports and spending time with his partner and son.
Read more about Ben Shaw

author image
Saurabh Badhwar

Saurabh Badhwar is an infrastructure engineer who works on building tools and frameworks that enhance developer productivity. A major part of his work involves using Python to develop services that scale to thousands of concurrent users. He is currently employed at LinkedIn and works on infrastructure performance tools and services.
Read more about Saurabh Badhwar

author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

author image
Bharath Chandra K S

Bharath Chandra K S lives in Sydney, Australia, and has over 14 years of software industry experience. He is very passionate about software development on the Python stack, including frameworks such as Flask and Django. He has experience working with both monolithic and microservice architectures and has built various public-facing applications and data processing backend systems. When not cooking up software applications, he likes to cook some nice food.
Read more about Bharath Chandra K S

author image
Chris Guest

Chris Guest is based in Melbourne and started programming in Python 24 years ago, when it was an obscure academic language. He has since used his Python knowledge in the publishing, hospitality, medical, academic and financial sectors. Throughout his career, he has worked with many Python web development frameworks, including Zope, TurboGears, web2py, and Flask, although he still prefers Django.
Read more about Chris Guest