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 - Second Edition
Web Development with Django - Second Edition

Web Development with Django: A definitive guide to building modern Python web applications using Django 4, Second Edition

By Ben Shaw , Saurabh Badhwar , Chris Guest , Bharath Chandra K S
S$59.99 S$41.98
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
Book May 2023 764 pages 2nd Edition
eBook
S$59.99 S$41.98
Print
S$74.99
Subscription
Free Trial
eBook
S$59.99 S$41.98
Print
S$74.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : May 26, 2023
Length 764 pages
Edition : 2nd Edition
Language : English
ISBN-13 : 9781803230603
Category :

Estimated delivery fee Deliver to Singapore

Premium 5 - 8 business days

S$54.95
(Includes tracking information)

Standard 10 - 13 business days

S$11.95
Table of content icon View table of contents Preview book icon Preview Book

Web Development with Django - Second Edition

An Introduction to Django

The web framework for perfectionists with deadlines.” It’s a tagline that aptly describes Django, a framework that has been around for over 10 years now. It is battle-tested and widely used, with more and more people using it every day. All this might make you think that Django is old and no longer relevant. On the contrary – its longevity has proved that its API is reliable and consistent, and even those who learned Django v1.0 in 2007 can mostly write the same code for Django 4 today. Django is still in active development, with bug fixes and security patches being released monthly.

Like Python, the language in which it is written, Django is easy to learn, yet powerful and flexible enough to grow with your needs. It is a “batteries-included” framework – in other words, you do not have to find and install many other libraries or components to get your application up and running. Other frameworks, such as...

Technical requirements

Throughout this book, you will be writing code. If you need to refer to the complete code for this chapter, you can find it in this GitHub repository: https://github.com/PacktPublishing/Web-Development-with-Django-Second-Edition/tree/main/Chapter01.

Scaffolding a Django project and app

Before diving deeply into the theory behind Django paradigms and HTTP requests, we’ll show you how easy it is to get a Django project up and running. After this first section and exercise, you will have created a Django project, made a request to it with your browser, and seen the response.

A Django project is a directory that contains all the data for your project – code, settings, templates, and assets. It is created and scaffolded by running the django-admin command on the command line with the startproject argument and providing the project name. For example, to create a Django project with the name myproject, the command that is run is as follows:

django-admin startproject myproject

This will create the myproject directory, which Django populates with the necessary files to run the project. Inside the myproject directory are two files (shown in Figure 1.1):

Figure 1.1 – The project directory for myproject

Figure 1.1 – The project directory...

Understanding the model-view-template paradigm

A common design pattern in application design is the Model View Controller (MVC), where the model of an application (its data) is displayed in one or more views, and a controller marshals interaction between the model and view. Django follows a different, yet similar, paradigm called the Model-View-Template (MVT).

Like MVC, MVT also uses models for storing data. However, with MVT, a view will query a model and then render it with a template. Usually, with MVC languages, all three components need to be developed with the same language. With MVT, the template can be in a different language. In the case of Django, models and views are written in Python, and the template is written in HTML. This means that a Python developer could work on the models and views, while a specialist HTML developer works on the HTML. We’ll first explain models, views, and templates in more detail and then look at some example scenarios where they are...

Exploring the Django project structure

We already introduced Django projects in the Scaffolding a Django project and app section. Let’s remind ourselves of what happens when we run startproject (for a project named myproject) – the command creates a myproject directory with one file called manage.py, and a directory called myproject (this matches the project name; in Exercise 1.01 – creating a project and app, and starting the development server, this folder was called bookr, the same as the project). The directory layout is shown in Figure 1.8. We’ll now examine the manage.py file and myproject package contents in more detail.

Figure 1.8 – The project directory for myproject

Figure 1.8 – The project directory for myproject

As the name suggests, manage.py is a script that is used to manage your Django project. Most of the commands that are used to interact with your project will be supplied to this script on the command line. The commands are supplied as an argument...

Introducing Django views

You now have everything set up to start writing your own Django views and configure the URLs that will map to them. As we saw earlier in this chapter, a view is simply a function that takes an HttpRequest instance (built by Django) and (optionally) some parameters from the URL. It will then perform some operations, such as fetching data from a database. Finally, it returns HttpResponse.

To use our Bookr app as an example, we might have a view that receives a request for a certain book. It queries the database for this book, and then returns a response containing an HTML page, showing information about the book. Another view could receive a request to list all the books, and then return a response with another HTML page containing this list. Views can also create or modify data; another view could receive a request to create a new book, and it would then add the book to the database and return a response with HTML that displays the new book’s information...

Exploring URL mapping detail

We briefly mentioned URL maps earlier in the Processing a request section. Django does not automatically know which view function should be executed when it receives a request for a particular URL. The role of URL mapping is to build a link between a URL and a view. For example, in Bookr, you might want to map the /books/ URL to a books_list view that you have created.

The URL-to-view mapping is defined in the file that Django automatically created called urls.py, inside the bookr package directory (although a different file can be set in settings.py; there’ll be more on that later).

This file contains a variable, urlpatterns, which is a list of paths that Django evaluates in turn until it finds a match for the URL being requested. The match will either resolve to a view function or another urls.py file, also containing a urlpatterns variable, which will be resolved in the same manner. URL files can be chained in this manner for as long as...

Working with GET, POST, and QueryDict objects

Data can come through an HTTP request as parameters on a URL or inside the body of a POST request. You might have noticed parameters in a URL when browsing the web – the text after ? – for example, http://www.example.com/?parameter1=value1&parameter2=value2. We also saw earlier in this chapter an example of form data in a POST request to log in a user (the request body was username=user&password=password1).

Django automatically parses these parameter strings into QueryDict objects. The data is then available on the HttpRequest object that is passed to your view – specifically, in the HttpRequest.GET and HttpRequest.POST attributes for URL parameters and body parameters respectively. QueryDict objects mostly behave like dictionaries, except that they can contain multiple values for a key.

To show different methods of accessing items in, we’ll use a simple QueryDict (the qd variable) with only one...

Exploring Django settings

We haven’t yet looked at how Django stores its settings. Now that we’ve seen the different parts of Django, it is a good time to examine the settings.py file. There are many settings Django contains that can be used to customize it. A default settings.py file was created for you when you started the Bookr project. We will discuss some of the more important settings in the file now, and a few others that might be useful as you become more fluent with Django. You should open your settings.py file in PyCharm and follow along so that you can see where and what the values are for your project.

Each setting in this file is just a file-global variable. The order in which we will discuss the settings is the same order in which they appear in this file, although we may skip over some – for example, there is the ALLOWED_HOSTS setting between DEBUG and INSTALLED_APPS, which we won’t cover in this part of the book (you’ll see it in...

Finding HTML templates in app directories

There are many options that are available to tell Django how to find templates, which can be set in the TEMPLATES setting of settings.py, but the easiest one (for now) is to create a templates directory inside the reviews directory. Django will look in this (and in other apps’ templates directories) because of APP_DIRS being True in the settings.py file, as we saw in the previous section. However, for Django to know that the reviews directory is an app, we need to configure it in the settings. We’ll do that in the next exercise.

Exercise 1.05 – creating a templates directory and a base template

In this exercise, you will create a templates directory for the reviews app. Then, you will add an HTML template file that Django will be able to render to an HTTP response.

We discussed settings.py and its INSTALLED_APPS setting in the Exploring Django settings section. We need to add the reviews app to INSTALLED_APPS for...

Debugging and dealing with errors

When programming, unless you’re the perfect programmer who never makes mistakes, you’ll probably have to deal with errors or debug your code at some point. When there is an error in your program, there are usually two ways to tell – either your code will raise an exception, or you will get unexpected output or results when viewing the page. You will probably see exceptions more often, as there are many accidental ways to cause them. If your code is generating unexpected output but not raising any exceptions, you will probably want to use the PyCharm debugger to find out why.

We’ll start with an overview of some Python exceptions and how to handle them, along with an exercise that demonstrates how Django shows exceptions. Then, we’ll look at running Django inside the PyCharm debugger so that you can peek inside your program while it executes.

Exceptions

If you have worked with Python or other programming languages...

Activity 1.01 – creating a site welcome screen

The Bookr website that we are building needs to have a splash page that welcomes users and lets them know what site they are on. It will also contain links to other parts of the site, but these will be added in later chapters. For now, you will create a page with a welcome message.

These steps will help you complete the activity:

  1. In your index view, render the base.html template.
  2. Update the base.html template to contain the welcome message. It should be in both the <title> tag in <head> and in a new <h1> tag in the body.

After completing the activity, you should be able to see something like this:

Figure 1.52 – The Bookr welcome page

Figure 1.52 – The Bookr welcome page

Note

The solution for this activity can be found on https://github.com/PacktPublishing/Web-Development-with-Django-Second-Edition/tree/main/ActivitySolutions.

In the next activity, you will build a basic page to show...

Activity 1.02 – a book search scaffold

A useful feature of a site such as Bookr is the ability to search through data to find something on the site quickly. Bookr will implement book searching to allow users to find a particular book by part of its title. While we don’t have any books to find yet, we can still implement a page that shows the text a user searched for. The user enters the search string as part of the URL parameters. We will implement searching and a form for easy text entry in Chapter 6, Forms.

These steps will help you complete the activity:

  1. Create a search result HTML template. It should include a variable placeholder to show the search word(s) that were passed in through the render context. Show the passed-in variable in the <title> and <h1> tags. Use an <em> tag around the search text in the body to make it italic.
  2. Add a search view function in views.py. The view should read a search string from the URL parameters (in...

Summary

This chapter was a quick introduction to Django. You first got up to speed on the HTTP protocol and the structure of HTTP requests and responses. We then saw how Django uses the MVT paradigm, and then how it parses a URL, generates an HTTP request, and sends it to a view to get an HTTP response. We scaffolded the Bookr project and then created the reviews app for it. We then built two example views to illustrate how to get data from a request and use it when rendering templates. You also experimented to see how Django escapes output in HTML when rendering a template.

We did all this with the PyCharm IDE, and you learned how to set it up to debug your application. The debugger will help you find out why things aren’t working as they should.

In the next chapter, you will start to learn about Django’s database integration and its model system, so you can start storing and retrieving real data for your application.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Understand Django functionality and the Model-View-Template (MVT) paradigm
  • Create and iteratively build a book review website, adding features as you build your knowledge
  • Explore advanced concepts such as REST API implementation and third-party module integration

Description

Do you want to develop reliable and secure applications that stand out from the crowd without spending hours on boilerplate code? You’ve made the right choice trusting the Django framework, and this book will tell you why. Often referred to as a “batteries included” web development framework, Django comes with all the core features needed to build a standalone application. Web Development with Django will take you through all the essential concepts and help you explore its power to build real-world applications using Python. Throughout the book, you’ll get the grips with the major features of Django by building a website called Bookr – a repository for book reviews. This end-to-end case study is split into a series of bitesize projects presented as exercises and activities, allowing you to challenge yourself in an enjoyable and attainable way. As you advance, you'll acquire various practical skills, including how to serve static files to add CSS, JavaScript, and images to your application, how to implement forms to accept user input, and how to manage sessions to ensure a reliable user experience. You’ll cover everyday tasks that are part of the development cycle of a real-world web application. By the end of this Django book, you'll have the skills and confidence to creatively develop and deploy your own projects.

What you will learn

Create a new application and add models to describe your data Use views and templates to control behavior and appearance Implement access control through authentication and permissions Develop practical web forms to add features such as file uploads Build a RESTful API and JavaScript code that communicates with it Connect to a database such as PostgreSQL

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : May 26, 2023
Length 764 pages
Edition : 2nd Edition
Language : English
ISBN-13 : 9781803230603
Category :

Estimated delivery fee Deliver to Singapore

Premium 5 - 8 business days

S$54.95
(Includes tracking information)

Standard 10 - 13 business days

S$11.95

Table of Contents

19 Chapters
Preface Chevron down icon Chevron up icon
1. Chapter 1: An Introduction to Django Chevron down icon Chevron up icon
2. Chapter 2: Models and Migrations Chevron down icon Chevron up icon
3. Chapter 3: URL Mapping, Views, and Templates Chevron down icon Chevron up icon
4. Chapter 4: An Introduction to Django Admin Chevron down icon Chevron up icon
5. Chapter 5: Serving Static Files Chevron down icon Chevron up icon
6. Chapter 6: Forms Chevron down icon Chevron up icon
7. Chapter 7: Advanced Form Validation and Model Forms Chevron down icon Chevron up icon
8. Chapter 8: Media Serving and File Uploads Chevron down icon Chevron up icon
9. Chapter 9: Sessions and Authentication Chevron down icon Chevron up icon
10. Chapter 10: Advanced Django Admin and Customizations Chevron down icon Chevron up icon
11. Chapter 11: Advanced Templating and Class-Based Views Chevron down icon Chevron up icon
12. Chapter 12: Building a REST API Chevron down icon Chevron up icon
13. Chapter 13: Generating CSV, PDF, and Other Binary Files Chevron down icon Chevron up icon
14. Chapter 14: Testing Your Django Applications Chevron down icon Chevron up icon
15. Chapter 15: Django Third-Party Libraries Chevron down icon Chevron up icon
16. Chapter 16: Using a Frontend JavaScript Library with Django Chevron down icon Chevron up icon
17. Index Chevron down icon Chevron up icon
18. Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(1 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


N/A Jan 29, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo image
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.