Reader small image

You're reading from  Django 5 By Example - Fifth Edition

Product typeBook
Published inApr 2024
PublisherPackt
ISBN-139781805125457
Edition5th Edition
Right arrow
Author (1)
Antonio Melé
Antonio Melé
author image
Antonio Melé

Antonio Melé has been crafting Django projects since 2006, for clients spanning multiple industries. He is Engineering Director at Backbase, a leading global fintech firm dedicated to facilitating the digital transformation of financial institutions. He co-founded Nucoro, a digital wealth management platform. In 2009 Antonio founded Zenx IT, a company specialized in developing digital products. He has been working as CTO and consultant for several tech-centric startups. He has also managed development teams building projects for large enterprise clients. He has an MSc in Computer Science from Universidad Pontificia Comillas and completed the Advanced Management Program at MIT Sloan. His father inspired his passion for computers and coding.
Read more about Antonio Melé

Right arrow

Rendering and Caching Content

In the previous chapter, you used model inheritance and generic relations to create flexible course content models. You implemented a custom model field and you built a course management system using class-based views. Finally, you created a JavaScript drag-and-drop functionality using asynchronous HTTP requests to order course modules and their contents.

In this chapter, you will build the functionality to create a student registration system and manage student enrollment in courses. You will implement rendering of the different types of course content and learn how to cache data using the Django cache framework.

Rendering diverse content types is essential in e-learning platforms, where courses are typically structured with flexible modules that include a mix of text, images, videos, and documents. In this context, caching also becomes crucial. Since course content usually remains unchanged for extended periods – days, weeks, or even...

Functional overview

Figure 14.1 shows a representation of the views, templates, and functionalities that will be built in this chapter:

Figure 14.1: Diagram of functionalities built in Chapter 14

In this chapter, you will implement the CourseListView public view to list courses and CourseDetailView to show the details of a course. You will implement StudentRegistrationView to allow students to create user accounts and StudentCourseListView for students to enroll in courses. You will create the StudentCourseListView for students to see the list of courses they are enrolled in and the StudentCourseDetailView to access all the content of a course, organized in the different course modules. You will also add a cache to your views using the Django cache framework, first with the Memcached backend and then replacing it with the Redis cache backend.

The source code for this chapter can be found at https://github.com/PacktPublishing/Django-5-by-example/tree/main/Chapter14...

Displaying the catalog of courses

You might be eager to get to rendering and caching but there are a few items we must set up before we can do that. Let’s start with the course catalog. For your course catalog, you have to build the following functionalities:

  • List all available courses, optionally filtered by subject
  • Display a single course overview

This will allow students to see all the courses available on the platform and enroll in those they are interested in. Edit the views.py file of the courses application and add the following code:

from django.db.models import Count
from .models import Subject
class CourseListView(TemplateResponseMixin, View):
    model = Course
    template_name = 'courses/course/list.html'
    def get(self, request, subject=None):
        subjects = Subject.objects.annotate(
            total_courses=Count('courses')
        )
        courses = Course.objects.annotate(
            total_modules=Count...

Adding student registration

We need to implement student registration to enable enrollment in courses and access to content. Create a new application using the following command:

python manage.py startapp students

Edit the settings.py file of the educa project and add the new application to the INSTALLED_APPS setting, as follows:

INSTALLED_APPS = [
    # ...
    'students.apps.StudentsConfig',
]

Creating a student registration view

Edit the views.py file of the students application and write the following code:

from django.contrib.auth import authenticate, login
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView
class StudentRegistrationView(CreateView):
    template_name = 'students/student/registration.html'
    form_class = UserCreationForm
    success_url = reverse_lazy('student_course_list')
    def form_valid(self, form):
        result...

Rendering course contents

Once students are enrolled in courses, they need a central location to access all courses they are signed up for. We need to compile the list of courses the student is enrolled in and provide access to the contents of each course. Then, we need to implement a system to render various types of content, such as text, images, videos and documents, which make up the course modules. Let’s build the necessary views and templates for users to access course contents.

Accessing course contents

You need a view for displaying the courses that students are enrolled in and a view for accessing the actual course contents. Edit the views.py file of the students application and add the following code to it:

from django.views.generic.list import ListView
from courses.models import Course
class StudentCourseListView(LoginRequiredMixin, ListView):
    model = Course
    template_name = 'students/course/list.html'
    def get_queryset(self):
   ...

Using the cache framework

Processing HTTP requests to your web application usually entails database access, data manipulation, and template rendering. It is much more expensive in terms of processing than just serving a static website. The overhead in some requests can be significant when your site starts getting more and more traffic. This is where caching becomes essential. By caching queries, calculation results, or rendered content in an HTTP request, you will avoid expensive operations in the following requests that need to return the same data. This translates into shorter response times and less processing on the server side.

Django includes a robust cache system that allows you to cache data with different levels of granularity. You can cache a single query, the output of a specific view, parts of rendered template content, or your entire site. Items are stored in the cache system for a default time, but you can specify the timeout when you cache data.

This is how...

Installing Memcached

Memcached is a popular high-performance, memory-based cache server. We are going to use Memcached and the PyMemcacheCache Memcached backend.

Installing the Memcached Docker image

Run the following command from the shell to pull the Memcached Docker image:

docker pull memcached:1.6.26

This will download the Memcached Docker image to your local machine. You can find more information about the official Memcached Docker image at https://hub.docker.com/_/memcached. If you don’t want to use Docker, you can also download Memcached from https://memcached.org/downloads.

Run the Memcached Docker container with the following command:

docker run -it --rm --name memcached -p 11211:11211 memcached:1.6.26 -m 64

Memcached runs on port 11211 by default. The -p option is used to publish the 11211 port to the same host interface port. The -m option is used to limit the memory for the container to 64 MB. Memcached runs in memory, and it is allotted...

Django cache settings

Django provides the following cache settings:

  • CACHES: A dictionary containing all available caches for the project.
  • CACHE_MIDDLEWARE_ALIAS: The cache alias to use for storage.
  • CACHE_MIDDLEWARE_KEY_PREFIX: The prefix to use for cache keys. Set a prefix to avoid key collisions if you share the same cache between several sites.
  • CACHE_MIDDLEWARE_SECONDS: The default number of seconds to cache pages.

The caching system for the project can be configured using the CACHES settings. This setting allows you to specify the configuration for multiple caches. Each cache included in the CACHES dictionary can specify the following data:

  • BACKEND: The cache backend to use.
  • KEY_FUNCTION: A string containing a dotted path to a callable that takes a prefix, version, and key as arguments and returns a final cache key.
  • KEY_PREFIX: A string prefix for all cache keys, to avoid collisions.
  • LOCATION: The location of the...

Cache levels

Django provides the following levels of caching, listed here by ascending order of granularity:

  • Low-level cache API: Provides the highest granularity. Allows you to cache specific queries or calculations.
  • Template cache: Allows you to cache template fragments.
  • Per-view cache: Provides caching for individual views.
  • Per-site cache: The highest-level cache. It caches your entire site.

Think about your cache strategy before implementing caching. Focus first on expensive queries or calculations that are not calculated on a per-user basis.

In the upcoming sections, we will explore how to use each of these caching levels in our project.

Let’s start by learning how to use the low-level cache API in your Python code.

Using the low-level cache API

The low-level cache API allows you to store objects in the cache with any granularity. It is located at django.core.cache. You can import it like this:

from...

Using the Redis cache backend

Django also provides a Redis cache backend. Let’s change the settings to use Redis instead of Memcached as the cache backend for the project. Remember that you already used Redis in Chapter 7, Tracking User Actions, and in Chapter 10, Extending Your Shop.

Install redis-py in your environment using the following command:

python -m pip install redis==5.0.4

Then, edit the settings.py file of the educa project and modify the CACHES setting, as follows:

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.redis.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379',
    }
}

The project will now use the RedisCache cache backend. The location is defined in the format redis://[host]:[port]. You use 127.0.0.1 to point to the localhost and 6379, which is the default port for Redis.

You can read more about the Redis cache backend at https://docs.djangoproject...

Summary

In this chapter, you implemented the public views for the course catalog. You built a system for students to register and enroll in courses. You also created the functionality to render different types of content for the course modules. Finally, you learned how to use the Django cache framework and you used the Memcached and Redis cache backends for your project.

In the next chapter, you will build a RESTful API for your project using Django REST framework and consume it using the Python Requests library.

Additional resources

The following resources provide additional information related to the topics covered in this chapter:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Django 5 By Example - Fifth Edition
Published in: Apr 2024Publisher: PacktISBN-13: 9781805125457
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

Author (1)

author image
Antonio Melé

Antonio Melé has been crafting Django projects since 2006, for clients spanning multiple industries. He is Engineering Director at Backbase, a leading global fintech firm dedicated to facilitating the digital transformation of financial institutions. He co-founded Nucoro, a digital wealth management platform. In 2009 Antonio founded Zenx IT, a company specialized in developing digital products. He has been working as CTO and consultant for several tech-centric startups. He has also managed development teams building projects for large enterprise clients. He has an MSc in Computer Science from Universidad Pontificia Comillas and completed the Advanced Management Program at MIT Sloan. His father inspired his passion for computers and coding.
Read more about Antonio Melé