Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Becoming an Enterprise Django Developer

You're reading from  Becoming an Enterprise Django Developer

Product type Book
Published in Jun 2022
Publisher Packt
ISBN-13 9781801073639
Pages 526 pages
Edition 1st Edition
Languages
Author (1):
Michael Dinder Michael Dinder
Profile icon Michael Dinder

Table of Contents (15) Chapters

Preface 1. Part 1 – Starting a Project
2. Chapter 1: Undertaking a Colossal Project 3. Chapter 2: Project Configuration 4. Chapter 3: Models, Relations, and Inheritance 5. Part 2 – Django Components
6. Chapter 4: URLs, Views, and Templates 7. Chapter 5: Django Forms 8. Chapter 6: Exploring the Django Admin Site 9. Chapter 7: Working with Messages, Email Notifications, and PDF Reports 10. Part 3 – Advanced Django Components
11. Chapter 8: Working with the Django REST Framework 12. Chapter 9: Django Testing 13. Chapter 10: Database Management 14. Other Books You May Enjoy

Chapter 4: URLs, Views, and Templates

In this chapter, we will build the URL patterns that route to different views, processing a request sent to the server. One of the jobs of a view is to send processed information in the form of context to a template that will be used to render static or dynamically changing content. By the end of this chapter, we will have created several URL patterns for the user to visit and view data. Some examples will trigger errors or not-found exceptions on purpose to help demonstrate the concepts provided in this chapter.

Django is based on what is called the Model-Template-View (MTV) architectural design pattern, which is similar to the well-known Model-View-Controller (MVC) design pattern used for a variety of popular web-based software systems today. The view in both of these architectural design patterns is what sometimes confuses people who are starting to learn Django and come from an MVC background. In both patterns, the model is the same, and...

Technical requirements

To work with the code in this chapter, the following tools will need to be installed on your local machine:

  • Python version 3.9 – used as the underlying programming language for the project
  • Django version 4.0 – used as the backend framework of the project
  • pip package manager – used to manage third-party Python/Django packages

We will continue to work with the solution created in Chapter 2, Project Configuration. However, it is not necessary to use the Visual Studio IDE. The main project itself can be run using another IDE or run independently using a terminal or command-line window from within the project root folder. This is where the manage.py file resides. Whatever editor or IDE you are using, a virtual environment will also be needed to work with the Django project. Instructions for how to create a project and virtual environment can be found in Chapter 2, Project Configuration. You will need a database to store...

Preparing for this chapter

Start by creating a new app in your project called chapter_4 by following the steps discussed in Chapter 2, Project Configuration, in the subsection titled Creating a Django app. As discussed in that section, don't forget to change the value of your name = variable for your app class found in the /becoming_a_django_entdev/becoming_a_django_entdev/chapter_4/apps.py file to now point to the path where you installed your app. Be sure to also include this app in your INSTALLED_APPS variable found in the settings.py file as well.

Configuring URL patterns

Django controls and processes URL patterns in what it calls a URL dispatcher. Django starts with the urls.py file, which is specified as the ROOT_URLCONF variable, found in the settings.py file. Visual Studio automatically created the ROOT_URLCONF variable for us when we created a project and it should have also done so when executing the Django startproject command.

If your project did not create this variable, add the following setting to your settings.py file:

# /becoming_a_django_entdev/settings.py
...
ROOT_URLCONF = 'becoming_a_django_entdev.urls'

The urls.py file defined in the ROOT_URLCONF variable is what Django considers the root URLconf of any project, short for URL configuration. Other url.py files can be linked together by importing them using an import() function. Django looks for only one thing in these urls.py files, a single variable named urlpatterns, which contains a set of URL patterns that have been defined for...

Mapping URL patterns

Writing custom views is a way for us to perform all of the tasks and services needed to render a page that includes all of the content that we want. Within a view, we can validate against business logic rules to determine how to handle a request.

In this exercise, we will use the year pattern that we wrote earlier in this chapter, to only allow a year greater than 1900. Anything less than that, we will tell Django to serve up a 404 response.

Using simple views

A simple view is also known as a method-based view, which is a callable function in Python.

Follow these steps to map to a simple view in your project:

  1. In your /chapter_4/urls.py file, revert to using the same converter class that we wrote in the Using path converters subsection of this chapter. Reference a view that we will write next in a different file called practice_view(), as highlighted here:
    # /becoming_a_django_entdev/chapter_4/urls.py 
    ...
    from django.urls 
    import ..., register_converter...

Resolving URLs

Resolving a URL is the process of taking a relative path or object and obtaining the URL that relates to a unique field such as a primary key. Django's reverse resolution of URL patterns is a method of generating a URL structure using argument values that we provide instead of hardcoding URL paths in places, which can break over time. We can use template tags and statements throughout the project to use the name argument of a URL pattern. This is encouraged as best practice and follows a DRY design principle, which is less prone to breakage as your project evolves.

Let's discuss how to use the name attribute to get a reverse resolution pattern.

Naming URL patterns

Using the same custom YearConverter class and the same my_year_path URL pattern that we created earlier in this chapter, do the following to configure your URL pattern.

In your /chapter_4/urls.py file, you should have the path shown in the following code block, using the highlighted name...

Resolving absolute URLs

An absolute URL includes the scheme, host, and port of a URL, as in the following format, scheme://host:port/path?query. This is an example of an absolute URL: https://www.example.com:8000/my_path?query=my_query_value.

Next, we will resolve an absolute URL while introducing the practice of using custom context processors.

Creating a context processor

Context processors are useful in many ways: they provide context that is shared globally among all templates and views within a project. Alternatively, the context being created in a view can only be used by the template that the view is using and no other templates. In the next example, we will create and then activate a custom global context processor where we will add the base URL of the site. We will call the context variable base_url, referring to scheme://host:port of the URL found throughout this project's site.

Follow these steps to create your context processor:

  1. In the same folder...

Working with complex views

A view method will suffice for a lot of different situations. For more robust and large-scale projects, we can apply a few tricks to make these views more adaptable in complicated use cases. Class-based views are used when writing adaptable and reusable applications.

Class-based views

With class-based views, we can write code that can be reused and extended easily. Just like when we extended models in Chapter 3, Models, Relations, and Inheritance, we can extend view classes in the exact same way, whereas function-based view methods cannot provide this ability. Two templates have been provided with the source code of this book to be used in the next exercise. These two files are the exact same file as the my_vehicle.html file, except that the title of the <h1> tag in each has been changed to VehicleView Class 1 and VehicleView Class 2 so that when we run the following examples, we can see the differences between them.

Follow these steps to configure...

Working with templates

The Django template language provides us with a set of template tags and template filters that are used to perform simple actions directly within a template. It makes it easy to perform simple logic operations, such as Python operations. Tags and filters are actually two different things that closely resemble each other. The Django template language can be closely compared to Shopify's Liquid syntax and is similar to the Razor syntax used in ASP.NET frameworks, but the Django template language is a bit easier to use and read. Django also allows us to create custom tags and filters for use within a project. Custom filters are most commonly used to transform a single context variable. Custom tags provide for more robust and complex use cases. For a complete breakdown of all of the template tags and template filters that exist, read the official Django documentation about them here: https://docs.djangoproject.com/en/4.0/ref/templates/builtins/.

Next, we...

Summary

By now, we have constructed what might feel like an entire project, but in reality, an application will consist of so much more than what was covered in this chapter. What we do have is a way to route URL paths to views and render different contexts in each template used. We learned how we can query the database in a view to get the data that we want to render in a template. We even covered the different ways we can handle and process an error page or simply redirect a URL to another path. We even used class-based views to write reusable class structures, making a project more adaptable to change in the long run.

In the next chapter, we will discuss how we can use form objects in combination with the function-based and class-based views and templates we learned how to create in this chapter.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Becoming an Enterprise Django Developer
Published in: Jun 2022 Publisher: Packt ISBN-13: 9781801073639
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}