Reader small image

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

Product typeBook
Published inAug 2022
Reading LevelBeginner
PublisherPackt
ISBN-139781801813051
Edition4th Edition
Languages
Tools
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

Enhancing Your Blog with Advanced Features

In the preceding chapter, we learned the main components of Django by developing a simple blog application. We created a simple blog application using views, templates, and URLs. In this chapter, we will extend the functionalities of the blog application with features that can be found in many blogging platforms nowadays. In this chapter, you will learn the following topics:

  • Using canonical URLs for models
  • Creating SEO-friendly URLs for posts
  • Adding pagination to the post list view
  • Building class-based views
  • Sending emails with Django
  • Using Django forms to share posts via email
  • Adding comments to posts using forms from models

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

All Python packages used in this chapter are included in the requirements.txt file in the source code for the chapter. You can follow...

Using canonical URLs for models

A website might have different pages that display the same content. In our application, the initial part of the content for each post is displayed both on the post list page and the post detail page. A canonical URL is the preferred URL for a resource. You can think of it as the URL of the most representative page for specific content. There might be different pages on your site that display posts, but there is a single URL that you use as the main URL for a post. Canonical URLs allow you to specify the URL for the master copy of a page. Django allows you to implement the get_absolute_url() method in your models to return the canonical URL for the object.

We will use the post_detail URL defined in the URL patterns of the application to build the canonical URL for Post objects. Django provides different URL resolver functions that allow you to build URLs dynamically using their name and any required parameters. We will use the reverse() utility function...

Creating SEO-friendly URLs for posts

The canonical URL for a blog post detail view currently looks like /blog/1/. We will change the URL pattern to create SEO-friendly URLs for posts. We will be using both the publish date and slug values to build the URLs for single posts. By combining dates, we will make a post detail URL to look like /blog/2022/1/1/who-was-django-reinhardt/. We will provide search engines with friendly URLs to index, containing both the title and date of the post.

To retrieve single posts with the combination of publication date and slug, we need to ensure that no post can be stored in the database with the same slug and publish date as an existing post. We will prevent the Post model from storing duplicated posts by defining slugs to be unique for the publication date of the post.

Edit the models.py file and add the following unique_for_date parameter to the slug field of the Post model:

class Post(models.Model):
    # ...
    slug = models.SlugField...

Modifying the URL patterns

Let’s modify the URL patterns to use the publication date and slug for the post detail URL.

Edit the urls.py file of the blog application and replace the line:

path('<int:id>/', views.post_detail, name='post_detail'),

With the lines:

path('<int:year>/<int:month>/<int:day>/<slug:post>/',
         views.post_detail,
         name='post_detail'),

The urls.py file should now look like this:

from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
    # Post views
    path('', views.post_list, name='post_list'),
    path('<int:year>/<int:month>/<int:day>/<slug:post>/',
         views.post_detail,
         name='post_detail'),
]

The URL pattern for the post_detail view takes the following arguments:

  • year: Requires an integer
  • month: Requires...

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

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.

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])

Start the development server by typing the following command in the shell prompt:

python manage.py runserver

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.1: The page for the post’s detail view

Take a look at the URL—it should look like /blog/2022/1/1/who-was-django-reinhardt...

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.2 shows Google’s pagination links for search result pages:

Figure 2.2: 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...

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

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

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

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.

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 2022Publisher: PacktISBN-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.
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 $15.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é