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

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

Product type Book
Published in Apr 2024
Publisher Packt
ISBN-13 9781805125457
Pages 820 pages
Edition 5th 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 and Adding Social 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

Modifying the views

Now we have to change the parameters of the post_detail view to match the new URL parameters and use them to retrieve the corresponding Post object.

Edit the views.py file and edit the post_detail view like this:

def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post,
                             status=Post.Status.PUBLISHED,
                             slug=post,
                             publish__year=year,
                             publish__month=month,
                             publish__day=day)
    return render(request,
                  'blog/post/detail.html',
                  {'post': post})

We have modified the post_detail view to take the year, month, day, and post arguments and retrieve a published post with the given slug and publication date. By adding unique_for_date='publish' to the slug field of the Post model before, we ensured that there will be only one post with a slug for...

Modifying the canonical URL for posts

We also have to modify the parameters of the canonical URL for blog posts to match the new URL parameters.

  1. Edit the models.py file of the blog application and edit the get_absolute_url() method as follows:
class Post(models.Model):
    # ...
    def get_absolute_url(self):
        return reverse('blog:post_detail',
                       args=[self.publish.year,
                             self.publish.month,
                             self.publish.day,
                             self.slug])
  1. Start the development server by typing the following command in the shell prompt:
python manage.py runserver
  1. Next, you can return to your browser and click on one of the post titles to take a look at the detail view of the post. You should see something like this:
Figure 2.2: The page for the post’s detail view

Take a look at the URL—it should look like /blog/2024/1/1/who-was-django-reinhardt/. You have designed...

Adding pagination

When you start adding content to your blog, you can easily store tens or hundreds of posts in your database. Instead of displaying all the posts on a single page, you may want to split the list of posts across several pages and include navigation links to the different pages. This functionality is called pagination, and you can find it in almost every web application that displays long lists of items.

For example, Google uses pagination to divide search results across multiple pages. Figure 2.3 shows Google’s pagination links for search result pages:

Figure 2.3: Google pagination links for search result pages

Django has a built-in pagination class that allows you to manage paginated data easily. You can define the number of objects you want to be returned per page and you can retrieve the posts that correspond to the page requested by the user.

Adding pagination to the post list view

Edit the views.py file of the blog application to import the Django...

Building class-based views

We have built the blog application using function-based views. Function-based views are simple and powerful, but Django also allows you to build views using classes.

Class-based views are an alternative way to implement views as Python objects instead of functions. Since a view is a function that takes a web request and returns a web response, you can also define your views as class methods. Django provides base view classes that you can use to implement your own views. All of them inherit from the View class, which handles HTTP method dispatching and other common functionalities.

Why use class-based views

Class-based views offer some advantages over function-based views that are useful for specific use cases. Class-based views allow you to:

  • Organize code related to HTTP methods, such as GET, POST, or PUT, in separate methods, instead of using conditional branching
  • Use multiple inheritance to create reusable view classes (also known as mixins)

Using a class...

Recommending posts by email

Now, we will learn how to create forms and how to send emails with Django. We will allow users to share blog posts with others by sending post recommendations via email.

Take a minute to think about how you could use views, URLs, and templates to create this functionality using what you learned in the preceding chapter.

To allow users to share posts via email, we will need to:

  • Create a form for users to fill in their name, their email address, the recipient email address, and optional comments
  • Create a view in the views.py file that handles the posted data and sends the email
  • Add a URL pattern for the new view in the urls.py file of the blog application
  • Create a template to display the form

Creating forms with Django

Let’s start by building the form to share posts. Django has a built-in forms framework that allows you to create forms easily. The forms framework makes it simple to define the fields of the form, specify how they have to be displayed...

Creating a comment system

We will continue extending our blog application with a comment system that will allow users to comment on posts. To build the comment system, we will need the following:

  • A comment model to store user comments on posts
  • A form that allows users to submit comments and manages the data validation
  • A view that processes the form and saves a new comment to the database
  • A list of comments and a form to add a new comment that can be included in the post detail template

Creating a model for comments

Let’s start by building a model to store user comments on posts.

Open the models.py file of your blog application and add the following code:

class Comment(models.Model):
    post = models.ForeignKey(Post,
                             on_delete=models.CASCADE,
                             related_name='comments')
    name = models.CharField(max_length=80)
    email = models.EmailField()
    body = models.TextField()
    created = models.DateTimeField(auto_now_add...

Creating forms from models

We need to build a form to let users comment on blog posts. Remember that Django has two base classes that can be used to create forms: Form and ModelForm. We used the Form class to allow users to share posts by email. Now we will use ModelForm to take advantage of the existing Comment model and build a form dynamically for it.

Edit the forms.py file of your blog application and add the following lines:

from .models import Comment
class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ['name', 'email', 'body']

To create a form from a model, we just indicate which model to build the form for in the Meta class of the form. Django will introspect the model and build the corresponding form dynamically.

Each model field type has a corresponding default form field type. The attributes of model fields are taken into account for form validation. By default, Django creates a form field for each field...

Adding comments to the post detail template

We need to edit the blog/post/detail.html template to implement the following:

  • Display the total number of comments for a post
  • Display the list of comments
  • Display the form for users to add a new comment

We will start by adding the total number of comments for a post.

Edit the blog/post/detail.html template and change it as follows:

{% extends "blog/base.html" %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
  <h1>{{ post.title }}</h1>
  <p class="date">
    Published {{ post.publish }} by {{ post.author }}
  </p>
  {{ post.body|linebreaks }}
  <p>
    <a href="{% url "blog:post_share" post.id %}">
      Share this post
    </a>
  </p>
  {% with comments.count as total_comments %}
    <h2>
      {{ total_comments }} comment{{ total_comments|pluralize }}
    </h2>
  {% endwith %}
{% endblock %}

We use the Django ORM in...

Additional resources

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

Summary

In this chapter, you learned how to define canonical URLs for models. You created SEO-friendly URLs for blog posts, and you implemented object pagination for your post list. You also learned how to work with Django forms and model forms. You created a system to recommend posts by email and created a comment system for your blog.

In the next chapter, you will create a tagging system for the blog. You will learn how to build complex QuerySets to retrieve objects by similarity. You will learn how to create custom template tags and filters. You will also build a custom sitemap and feed for your blog posts and implement a full-text search functionality for your posts.

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 2024 Publisher: Packt ISBN-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.
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}