Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Django 5 for the Impatient
Django 5 for the Impatient

Django 5 for the Impatient : Learn the core concepts of Django to develop Python web applications , Second Edition

Arrow left icon
Profile Icon Daniel Correa Profile Icon Greg Lim
Arrow right icon
€13.99 €20.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (1 Ratings)
eBook Sep 2024 228 pages 2nd Edition
eBook
€13.99 €20.99
Paperback
€26.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Daniel Correa Profile Icon Greg Lim
Arrow right icon
€13.99 €20.99
Full star icon Full star icon Full star icon Full star icon Empty star icon 4 (1 Ratings)
eBook Sep 2024 228 pages 2nd Edition
eBook
€13.99 €20.99
Paperback
€26.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€13.99 €20.99
Paperback
€26.99
Subscription
Free Trial
Renews at €18.99p/m

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
Product feature icon AI Assistant (beta) to help accelerate your learning
Table of content icon View table of contents Preview book icon Preview Book

Django 5 for the Impatient

Installing Python and Django, and Introducing the Movies Store Application

Welcome to Django 5 for the Impatient! This book focuses on the key tasks and concepts to help you learn and build Django applications quickly. It is designed for those of you who don’t need all the details about Django, except for those that you really need to know. By the end of this book, you will be confident in creating your own Django projects.

So, what’s Django? Django is a free, open-source web framework for building modern Python web applications. Django helps you quickly build web apps by abstracting away many of the repetitive challenges involved in building a website, such as connecting to a database, handling security, enabling user authentication, creating URL routes, displaying content on a page through templates and forms, supporting multiple database backends, and setting up an admin interface.

This reduction in repetitive tasks allows developers to focus on building a web application’s functionality, rather than reinventing the wheel for standard web application functions.

Django is one of the most popular frameworks available and is used by established companies such as Instagram, Pinterest, Mozilla, and National Geographic. It is also easy enough to be used by start-ups and to build personal projects.

There are other popular frameworks, such as Flask in Python and Express in JavaScript (for more information on Express, see Beginning Node.js, Express & MongoDB Development by Greg Lim: https://www.amazon.com/dp/B07TWDNMHJ/). However, these frameworks only provide the minimum required functionality for a simple web page, and developers have to do more foundational work, such as installing and configuring third-party packages on their own for basic website functionality.

In this chapter, we are going to get acquainted with the application we are going to build, using Django 5, and get ready to develop our project by installing and setting up everything we need. By the end of the chapter, you will have successfully created your development environment.

In this chapter, we will be covering the following topics:

  • Introducing and installing Python
  • Introducing and installing Django
  • Creating and running a Django project
  • Understanding the Movies Store application
  • Introducing Django MVT architecture

Technical requirements

In this chapter, we will use Python 3.10+.

The code for this chapter is located at https://github.com/PacktPublishing/Django-5-for-the-Impatient-Second-Edition/tree/main/Chapter01/moviesstore.

The CiA video for this chapter can be found at https://packt.link/ygUpr

Introducing and installing Python

Python is a high-level programming language (https://www.python.org/), created in the late 1980s by Guido van Rossum. The name Python comes from the creator’s affection for the British comedy group Monty Python and not the “snake,” as is commonly believed.

Python has an open-source license, meaning that developers can modify, use, and redistribute its code for free without paying the original author.

Python is characterized as a friendly and easy-to-learn programming language. Python can be used to develop a wide range of applications, including web development, data analysis, artificial intelligence, scientific computing, and automation.

For now, let’s check whether we have Python installed and, if so, what version we have.

If you are using a Mac, open your Terminal. If you are using Windows, open Command Prompt. For convenience, we will refer to both the Terminal and Command Prompt as Terminal throughout the book.

We will need to check whether we have at least Python 3.10 in order to use Django 5. To do so, go to your Terminal and run the following commands:

  • For macOS, run this:
    python3 --version
  • For Windows, run this:
    python --version

This shows the version of Python you have installed. Make sure that the version is at least 3.10. If it isn’t, get the latest version of Python by going to https://www.python.org/downloads/ and installing the version for your OS. For Windows, you must select the Add python.exe to PATH option (to ensure that the Python interpreter can be accessed from any directory in the command prompt or Terminal), as shown in Figure 1.1:

Figure 1.1 – Installing Python on Windows

Figure 1.1 – Installing Python on Windows

After the installation, run the command again to check the version of Python installed.

The output should reflect the latest version of Python, such as Python 3.12.2 (at the time of writing), as shown in Figure 1.2:

Figure 1.2 – Checking the Python version on Windows

Figure 1.2 – Checking the Python version on Windows

Now that we have Python installed, let’s move on to introducing and installing Django.

Introducing and installing Django

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design (https://www.djangoproject.com/). Django makes it easier to build better web apps more quickly and with less code.

There are several ways to install Django; we will use pip to install Django in this book. pip is the standard package manager for Python to install and manage packages not part of the standard Python library. pip is automatically installed if you downloaded Python from https://www.python.org/.

First, check whether you have pip installed by going to the Terminal and running the following commands:

  • For macOS, run this:
    pip3
  • For Windows, run this:
    pip

If you have pip installed, the output should display a list of pip commands, as shown in Figure 1.3:

Figure 1.3 – Checking whether pip is installed on Windows

Figure 1.3 – Checking whether pip is installed on Windows

Next, to install Django, run the following commands:

  • For macOS, run this:
    pip3 install django==5.0
  • For Windows, run this:
    pip install django==5.0

The preceding command will retrieve the Django 5.0 code version and install it on your machine. Note that there may be newer versions available when you’re reading this book. However, we recommend continuing to use Django 5.0 to ensure that the code in this book will function correctly. After installation, close and reopen your Terminal.

To check whether you have installed Django, run the following commands.

  • For macOS, run this:
    python3 -m django
  • For Windows, run this:
    python -m django

Now, the output will show you all the Django commands you can use, as shown in Figure 1.4:

Figure 1.4 – The Django module commands on macOS

Figure 1.4 – The Django module commands on macOS

Over the course of the book, you will progressively be introduced to some of the preceding commands.

Note

It is also common to use virtual environments (such as the venv module) to manage your Python and Django projects and dependencies. For now, we will not use venv to get started quickly on Django. We will learn how to use and configure venv at the end of this book.

We have all the tools we need to create a Django project. Now, let’s move on to doing that.

Creating and running a Django project

Now that we have Django installed, we are ready to create our Django project.

There are several ways to create Django projects. In this book, we will use django-admin. django-admin is Django’s command-line utility for administrative tasks. It provides various commands to help you create, manage, and interact with Django projects, applications, and other related components.

In the Terminal, navigate to the folder where you want to create your project and run the following command:

django-admin startproject moviesstore

This will create a moviesstore folder in your current directory. This folder contains our Django application code. We will discuss its contents later. For now, let’s run our first website on the Django local web server.

In the Terminal, run the cd command to move into the created folder:

cd moviesstore

Then, run the following command:

  • For macOS, run this:
    python3 manage.py runserver
  • For Windows, run this:
    python manage.py runserver

When you run the aforementioned commands, you start the local web server on your machine (for local development purposes). There will be a URL link – http://127.0.0.1:8000/ (equivalent to http://localhost:8000). Open this link in a browser, and you will see the default landing page, as shown in Figure 1.5:

Figure 1.5 – The landing page of the Django project

Figure 1.5 – The landing page of the Django project

This means that your local web server is running and serving the landing page. Sometimes, you will need to stop the server in order to run other Python commands. To stop the local server, press Ctrl + C in the Terminal.

We executed our first Django project successfully. Now, it is time to introduce the application we will develop in this book.

Understanding the Movies Store application

The use of running examples is a prevalent approach found in programming literature. The running example serves as a means to illustrate the principles of a methodology, process, tool, or technique. In this book, we will define a Movies Store running example. We will revisit this running example throughout the book to explain many of the Django concepts and elements in a practical way.

The Movies Store will be a web-based platform where users access information about movies and can place orders to purchase them.

Now, let’s outline the application’s scope for this particular app:

  • The Home page will feature a welcoming message.
  • The About page will provide details about the Movies Store.
  • The Movies page will exhibit information on available movies and include a filter to search movies by name. Additionally, users can click on a specific movie to view its details and post reviews.
  • The Cart page will showcase the movies added to the cart, along with the total price to be paid. Users can also remove movies from the cart and proceed with purchases.
  • The Register page will present a form enabling users to sign up for accounts.
  • The Login page will present a form allowing users to log in to the application.
  • The Orders page will display the orders placed by the logged-in user.
  • The Admin panel will encompass sections to manage the store’s information, including creating, updating, deleting, and listing information.

The Movies Store will be developed using Django (Python), with a SQLite database and Bootstrap (a CSS framework). Further details about these components will be covered in the forthcoming chapters.

In Figure 1.6, you’ll find a class diagram outlining the application’s scope and design. The user class is depicted with its associated data (such as an id, username, email, and password) and is capable of placing orders. Each order consists of one or more items, which are linked to individual movies. Each movie will possess its respective data (including an id, name, price, description, and image). Lastly, users have the ability to create reviews for movies.

Figure 1.6 – The Movies Store class diagram

Figure 1.6 – The Movies Store class diagram

This book does not delve into the intricacies of class diagrams; hence, we won’t elaborate on additional details within the diagram (you can refer to this link for additional information about class diagrams: https://www.visual-paradigm.com/guide/uml-unified-modeling-language/uml-class-diagram-tutorial/). As you progress through the book, you’ll notice the correlation between code and this diagram. Serving as a blueprint, this diagram guides the construction of our application.

Note

Creating a class diagram before commencing coding aids in comprehending the application’s scope and identifying crucial data points. Additionally, it facilitates understanding the interconnections among various elements of the application. This diagram can be shared with team members or colleagues for feedback, allowing for adjustments as necessary. Due to its nature as a diagram, modifications can be implemented quickly. Otherwise, once the project has been coded, the cost of relocating data from one class to another increases significantly. Check the following statement from the book Building Microservices by Newman, S. (2015): “I tend to do much of my thinking in the place where the cost of change and the cost of mistakes is as low as it can be: the whiteboard.

Based on the previous scope, we will build a Movies Store app that will allow users to view and search for movies, as shown in Figure 1.7:

Figure 1.7 – The movies page with search functionality

Figure 1.7 – The movies page with search functionality

Users will be able to sign up, as shown in Figure 1.8:

Figure 1.8 – The Sign Up page

Figure 1.8 – The Sign Up page

Users will be able to log in, add movies to the cart, and make purchases, as shown in Figure 1.9:

Figure 1.9 – The shopping cart page

Figure 1.9 – The shopping cart page

Users will also be able to list, create, edit, and delete movie reviews, as shown in Figure 1.10:

Figure 1.10 – A specific movie page with its reviews

Figure 1.10 – A specific movie page with its reviews

Many other functionalities will be developed and explained across the book. Now, let’s see the architecture we will use to construct the Movies Store application.

Introducing the Django MVT architecture

There are various methodologies and approaches to design and code web applications. One approach involves consolidating all code into a single file to construct the entire web application. However, finding errors within such a file, often comprising thousands of lines of code, can be incredibly challenging. Alternatively, other strategies distribute code across different files and directories. Additionally, some approaches segment an application into multiple smaller applications dispersed across several servers, although managing the distribution of these servers presents its own set of challenges.

Organizing your code effectively presents challenges. This is why developers and computer scientists have created software architectural patterns. Software architectural patterns offer structural frameworks or layouts to address common software design issues. By leveraging these patterns, start-ups and inexperienced developers can avoid reinventing solutions for every new project. Various architectural patterns exist, including Model-View-Controller (MVC), Model-View-Template (MVT), layers, service-oriented, and microservices. Each pattern comes with its own set of pros and cons. Many frameworks, such as Django, adhere to specific patterns in constructing their applications.

In the case of Django, Django is based on the MVT pattern. This pattern is similar to MVC but with some differences in the responsibilities of each component:

  • Models: The model represents the data structure. In Django, models are Python classes that define the structure of the data and how it interacts with the database. Models handle tasks such as querying a database, performing CRUD (Create, Read, Update, Delete) operations, and enforcing data validation. In the case of the Movies Store app, Movie, Review, Order and the other classes from our class diagram will be coded as Django models.
  • Views: Views in Django are responsible for processing user requests and returning appropriate responses. Views typically receive HTTP requests from clients, fetch data from the database using models, and render templates to generate HTML responses. In Django, views are Python functions or classes that accept HTTP requests and return HTTP responses. In the case of the Movies Store app, we will create views and functions to handle the movies, accounts, and cart, among others.
  • Templates: Templates are used to generate HTML dynamically. They contain the application’s user interface and define how data from the views should be displayed to the users. In the case of the Movies Store app, we will create a template to allow users to log in, a template to list movies, and a template to display the shopping cart, among others.

The MVT pattern offers several benefits such as enhanced code separation, facilitated collaboration among multiple team members, simplified error identification, increased code reusability, and improved maintainability. Figure 1.11 illustrates the software architecture of the Movies Store, which we will develop throughout this book. While it may seem overwhelming now, you will understand the intricacies of this architecture by the book’s conclusion. We will delve deeper into the architecture in the final chapters.

Figure 1.11 – The Movies Store software architecture diagram

Figure 1.11 – The Movies Store software architecture diagram

Let’s briefly analyze this architecture:

  • Positioned on the left are the clients, which are the users of our application, who use browsers on mobile or desktop devices. These clients establish connections with the application via the Hypertext Transfer Protocol (HTTP), providing users with a means to interact with our web application.
  • On the right side, we have the server, which hosts our application code.
  • All client interactions first pass for a project-level URL file called urls.py. This file is located in the main project folder called moviesstore/. URLs will be explored in Chapter 2. This project folder also contains a templates/ folder in which we will design a reusable base template. Base templates will be explored in Chapter 3.
  • The project-level URL file passes the interaction to an app-level URL file. For this project, we will design and implement four Django apps – home, movies, cart, and accounts. Django apps will be explored in Chapter 2.
  • Each app-level URL file passes the interaction to a views.py file. Views will be explored in Chapter 2.
  • Views communicate with models, if required, and pass information to the templates, which are finally delivered to the clients as HTML, CSS, and JS code. Templates will be explored in Chapter 2, and models will be explored in Chapter 5.

In Figure 1.11, the Model, View, and Template layers are highlighted in gray, representing the common architectural pattern used in Django, which will be utilized throughout this book. We have four models corresponding to the classes defined in our class diagram (as previously shown in Figure 1.6). The user model does not appear in this diagram because we will reuse a built-in Django user model.

Therefore, as mentioned earlier, there are different approaches to implementing web applications with Django. There are even different ways to implement a Django MVT architecture. In the following chapters, we will see the advantages of adopting an MVT architecture, as presented in Figure 1.11.

Summary

In this chapter, we learned how to install and use Python, pip, and Django. We also learned how to create a new Django project and run a Django local web server. Then, we explained the scope of the Movies Store project. We also illustrated the application data and its relationships through a class diagram. Additionally, we presented an architecture diagram that showed the main components and elements of the Movies Store. These diagrams will serve as a blueprint to codify the Movies Store project in the upcoming chapters.

In the next chapter, we will look inside the project folder that Django has created for us to understand it better, and we will create our first Django app.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Develop web applications with Python and Django quickly
  • Understand Django features with concise explanations and learn how to use them in a practical way
  • Create a movie store app with a responsive user interface and deploy it to the cloud
  • Purchase of the print or Kindle book includes a free PDF eBook

Description

Learning Django can be a challenging and time-consuming activity without the right guidance. With hundreds of tutorials, loads of documentation, and unclear explanations out there, it’s easy to lose sight of what’s most important. This book stands out by teaching you how to use Django in just a few days with a focused approach. In this second edition, you’ll go on a fun, practical, and pragmatic journey to learning full-stack development with Django 5. You’ll start building your first Django app within minutes. As you progress, you’ll learn from concise explanations that will help you get to grips with some of the most important Django features, including URLs, views, templates, models, CSS inclusion, image storage, Django admin panel, and more. You’ll also understand how to design Django MVT (Model-View-Template) architectures and implement them. Additionally, you’ll use Django to develop a movie store application and deploy it to the internet. By the end of this book, you’ll be able to build and deploy your own Django web applications confidently.

Who is this book for?

This book is for Python developers of any experience level who want to build full-stack web applications using Django. Anyone new to Django can get started with this book.

What you will learn

  • Understand and use Django key features, including URLs, templates, models, and forms
  • Implement responsive user interfaces using Bootstrap
  • Manage data storage in databases effectively
  • Explore the powerful built-in admin interface with Django
  • Harness Django's powerful built-in authentication system
  • Deploy your Django project on the internet for users

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 27, 2024
Length: 228 pages
Edition : 2nd
Language : English
ISBN-13 : 9781835468333
Languages :
Tools :

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
Product feature icon AI Assistant (beta) to help accelerate your learning

Product Details

Publication date : Sep 27, 2024
Length: 228 pages
Edition : 2nd
Language : English
ISBN-13 : 9781835468333
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 94.97
Python Data Cleaning and Preparation Best Practices
€33.99
Django 5 for the Impatient
€26.99
Python Natural Language Processing Cookbook
€33.99
Total 94.97 Stars icon

Table of Contents

15 Chapters
Chapter 1: Installing Python and Django, and Introducing the Movies Store Application Chevron down icon Chevron up icon
Chapter 2: Understanding the Project Structure and Creating Our First App Chevron down icon Chevron up icon
Chapter 3: Designing a Base Template Chevron down icon Chevron up icon
Chapter 4: Creating a Movies App with Dummy Data Chevron down icon Chevron up icon
Chapter 5: Working with Models Chevron down icon Chevron up icon
Chapter 6: Collecting and Displaying Data from the Database Chevron down icon Chevron up icon
Chapter 7: Understanding the Database Chevron down icon Chevron up icon
Chapter 8: Implementing User Signup and Login Chevron down icon Chevron up icon
Chapter 9: Letting Users Create, Read, Update, and Delete Movie Reviews Chevron down icon Chevron up icon
Chapter 10: Implementing a Shopping Cart System Chevron down icon Chevron up icon
Chapter 11: Implementing Order and Item Models Chevron down icon Chevron up icon
Chapter 12: Implementing the Purchase and Orders Pages Chevron down icon Chevron up icon
Chapter 13: Deploying the Application to the Cloud Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(1 Ratings)
5 star 0%
4 star 100%
3 star 0%
2 star 0%
1 star 0%
N/A Nov 8, 2024
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
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.