Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Web Development with Django

You're reading from  Web Development with Django

Product type Book
Published in Feb 2021
Publisher Packt
ISBN-13 9781839212505
Pages 826 pages
Edition 1st Edition
Languages
Authors (5):
Ben Shaw Ben Shaw
Profile icon Ben Shaw
Saurabh Badhwar Saurabh Badhwar
Profile icon Saurabh Badhwar
Andrew Bird Andrew Bird
Profile icon Andrew Bird
Bharath Chandra K S Bharath Chandra K S
Profile icon Bharath Chandra K S
Chris Guest Chris Guest
Profile icon Chris Guest
View More author details

Table of Contents (17) Chapters

Preface
1. Introduction to Django 2. Models and Migrations 3. URL Mapping, Views, and Templates 4. Introduction to Django Admin 5. Serving Static Files 6. Forms 7. Advanced Form Validation and Model Forms 8. Media Serving and File Uploads 9. Sessions and Authentication 10. Advanced Django Admin and Customizations 11. Advanced Templating and Class-Based Views 12. Building a REST API 13. Generating CSV, PDF, and Other Binary Files 14. Testing 15. Django Third-Party Libraries 16. Using a Frontend JavaScript Library with Django

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 2021 Publisher: Packt ISBN-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.
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 $15.99/month. Cancel anytime}