Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Django 4 By Example - Fourth Edition

You're reading from  Django 4 By Example - Fourth Edition

Product type Book
Published in Aug 2022
Publisher Packt
ISBN-13 9781801813051
Pages 766 pages
Edition 4th Edition
Languages
Author (1):
Antonio Melé Antonio Melé
Profile icon Antonio Melé

Table of Contents (20) Chapters

Preface 1. Building a Blog Application 2. Enhancing Your Blog with Advanced Features 3. Extending Your Blog Application 4. Building a Social Website 5. Implementing Social Authentication 6. Sharing Content on Your Website 7. Tracking User Actions 8. Building an Online Shop 9. Managing Payments and Orders 10. Extending Your Shop 11. Adding Internationalization to Your Shop 12. Building an E-Learning Platform 13. Creating a Content Management System 14. Rendering and Caching Content 15. Building an API 16. Building a Chat Server 17. Going Live 18. Other Books You May Enjoy
19. Index

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 access course contents, create a student registration system, and manage student enrollment onto courses. You will also learn how to cache data using the Django cache framework.

In this chapter, you will:

  • Create public views for displaying course information
  • Build a student registration system
  • Manage student enrollment onto courses
  • Render diverse content for course modules
  • Install and configure Memcached
  • Cache content using the Django cache framework
  • Use the Memcached and Redis cache backends...

Displaying courses

For your course catalog, you have to build the following functionalities:

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

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('modules'))
        if subject:
            subject = get_object_or_404(Subject, slug=subject)
            courses = courses.filter(subject=subject)
        return self.render_to_response({'subjects': subjects,
                                        &apos...

Adding student registration

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.urls import reverse_lazy
from django.views.generic.edit import CreateView
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
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 = super().form_valid(form)
        cd = form.cleaned_data
        user = authenticate(username...

Accessing the course contents

You need a view for displaying the courses that students are enrolled on, 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):
        qs = super().get_queryset()
        return qs.filter(students__in=[self.request.user])

This is the view to see courses that students are enrolled on. It inherits from LoginRequiredMixin to make sure that only logged-in users can access the view. It also inherits from the generic ListView for displaying a list of Course objects. You override the get_queryset() method to retrieve only the courses that a student is enrolled on; you filter the QuerySet by the student’s ManyToManyField...

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 precious. 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 you...

Additional resources

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

Summary

In this chapter, you implemented the public views for the course catalog. You built a system for students to register and enroll on 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.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Django 4 By Example - Fourth Edition
Published in: Aug 2022 Publisher: Packt ISBN-13: 9781801813051
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}