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

Sharing Content on Your Website

In the previous chapter, you used Django Social Auth to add social authentication to your site using Facebook, Google, and Twitter. You learned how to run your development server with HTTPS on your local machine using Django Extensions. You customized the social authentication pipeline to create a user profile for new users automatically.

In this chapter, you will learn how to create a JavaScript bookmarklet to share content from other sites on your website, and you will implement AJAX features in your project using JavaScript and Django.

This chapter will cover the following points:

  • Creating many-to-many relationships
  • Customizing behavior for forms
  • Using JavaScript with Django
  • Building a JavaScript bookmarklet
  • Generating image thumbnails using easy-thumbnails
  • Implementing asynchronous HTTP requests with JavaScript and Django
  • Building infinite scroll pagination

The source code for this...

Creating an image bookmarking website

We will now learn how to allow users to bookmark images that they find on other websites and share them on our site. To build this functionality, we will need the following elements:

  1. A data model to store images and related information
  2. A form and a view to handle image uploads
  3. JavaScript bookmarklet code that can be executed on any website. This code will find images across the page and allow users to select the image they want to bookmark

First, create a new application inside your bookmarks project directory by running the following command in the shell prompt:

django-admin startapp images

Add the new application to the INSTALLED_APPS setting in the settings.py file of the project, as follows:

INSTALLED_APPS = [
    # ...
    'images.apps.ImagesConfig',
]

We have activated the images application in the project.

Building the image model

Edit the models.py file of the images application...

Posting content from other websites

We will allow users to bookmark images from external websites and share them on our site. Users will provide the URL of the image, a title, and an optional description. We will create a form and a view to download the image and create a new Image object in the database.

Let’s start by building a form to submit new images.

Create a new forms.py file inside the images application directory and add the following code to it:

from django import forms
from .models import Image
class ImageCreateForm(forms.ModelForm):
    class Meta:
        model = Image
        fields = ['title', 'url', 'description']
        widgets = {
            'url': forms.HiddenInput,
        }

We have defined a ModelForm form from the Image model, including only the title, url, and description fields. Users will not enter the image URL directly in the form. Instead, we will provide them with a JavaScript tool to choose...

Creating a detail view for images

Let’s now create a simple detail view to display images that have been bookmarked on the site. Open the views.py file of the images application and add the following code to it:

from django.shortcuts import get_object_or_404
from .models import Image
def image_detail(request, id, slug):
    image = get_object_or_404(Image, id=id, slug=slug)
    return render(request,
                  'images/image/detail.html',
                  {'section': 'images',
                   'image': image})

This is a simple view to display an image. Edit the urls.py file of the images application and add the following URL pattern highlighted in bold:

urlpatterns = [
    path('create/', views.image_create, name='create'),
    path('detail/<int:id>/<slug:slug>/',
         views.image_detail, name='detail'),
]

Edit the models.py file of the images application...

Creating image thumbnails using easy-thumbnails

We are displaying the original image on the detail page, but dimensions for different images may vary considerably. The file size for some images may be very large, and loading them might take too long. The best way to display optimized images in a uniform manner is to generate thumbnails. A thumbnail is a small image representation of a larger image. Thumbnails will load faster in the browser and are a great way to homogenize images of very different sizes. We will use a Django application called easy-thumbnails to generate thumbnails for the images bookmarked by users.

Open the terminal and install easy-thumbnails using the following command:

pip install easy-thumbnails==2.8.1

Edit the settings.py file of the bookmarks project and add easy_thumbnails to the INSTALLED_APPS setting, as follows:

INSTALLED_APPS = [
    # ...
    'easy_thumbnails',
]

Then, run the following command to sync the application...

Adding asynchronous actions with JavaScript

We are going to add a like button to the image detail page to let users click on it to like an image. When users click the like button, we will send an HTTP request to the web server using JavaScript. This will perform the like action without reloading the whole page. For this functionality, we will implement a view that allows users to like/unlike images.

The JavaScript Fetch API is the built-in way to make asynchronous HTTP requests to web servers from web browsers. By using the Fetch API, you can send and retrieve data from the web server without the need for a whole page refresh. The Fetch API was launched as a modern successor to the browser built-in XMLHttpRequest (XHR) object, used to make HTTP requests without reloading the page. The set of web development techniques to send and retrieve data from a web server asynchronously without reloading the page is also known as AJAX, which stands for Asynchronous JavaScript and XML. AJAX...

Adding infinite scroll pagination to the image list

Next, we need to list all bookmarked images on the website. We will use JavaScript requests to build an infinite scroll functionality. Infinite scroll is achieved by loading the next results automatically when the user scrolls to the bottom of the page.

Let’s implement an image list view that will handle both standard browser requests and requests originating from JavaScript. When the user initially loads the image list page, we will display the first page of images. When they scroll to the bottom of the page, we will retrieve the following page of items with JavaScript and append it to the bottom of the main page.

The same view will handle both standard and AJAX infinite scroll pagination. Edit the views.py file of the images application and add the following code highlighted in bold:

from django.http import HttpResponse
from django.core.paginator import Paginator, EmptyPage, \
                               ...

Additional resources

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

Summary

In this chapter, you created models with many-to-many relationships and learned how to customize the behavior of forms. You built a JavaScript bookmarklet to share images from other websites on your site. This chapter has also covered the creation of image thumbnails using the easy-thumbnails application. Finally, you implemented AJAX views using the JavaScript Fetch API and added infinite scroll pagination to the image list view.

In the next chapter, you will learn how to build a follow system and an activity stream. You will work with generic relations, signals, and denormalization. You will also learn how to use Redis with Django to count image views and generate an image ranking.

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é