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

Building a Social Website

In the preceding chapter, you learned how to implement a tagging system and how to recommend similar posts. You implemented custom template tags and filters. You also learned how to create sitemaps and feeds for your site, and you built a full-text search engine using PostgreSQL.

In this chapter, you will learn how to develop user account functionalities to create a social website, including user registration, password management, profile editing, and authentication. We will implement social features into this site in the next few chapters, to let users share images and interact with each other. Users will be able to bookmark any image on the internet and share it with other users. They will also be able to see activity on the platform from the users they follow and like/unlike the images shared by them.

This chapter will cover the following topics:

  • Creating a login view
  • Using the Django authentication framework
  • Creating templates...

Creating a social website project

We are going to create a social application that will allow users to share images that they find on the internet. We will need to build the following elements for this project:

  • An authentication system for users to register, log in, edit their profile, and change or reset their password
  • A follow system to allow users to follow each other on the website
  • Functionality to display shared images and a system for users to share images from any website
  • An activity stream that allows users to see the content uploaded by the people that they follow

This chapter will address the first point on the list.

Starting the social website project

Open the terminal and use the following commands to create a virtual environment for your project:

mkdir env
python -m venv env/bookmarks

If you are using Linux or macOS, run the following command to activate your virtual environment:

source env/bookmarks/bin/activate...

Using the Django authentication framework

Django comes with a built-in authentication framework that can handle user authentication, sessions, permissions, and user groups. The authentication system includes views for common user actions such as logging in, logging out, password change, and password reset.

The authentication framework is located at django.contrib.auth and is used by other Django contrib packages. Remember that we already used the authentication framework in Chapter 1, Building a Blog Application, to create a superuser for the blog application to access the administration site.

When we create a new Django project using the startproject command, the authentication framework is included in the default settings of our project. It consists of the django.contrib.auth application and the following two middleware classes found in the MIDDLEWARE setting of our project:

  • AuthenticationMiddleware: Associates users with requests using sessions
  • SessionMiddleware...

User registration and user profiles

Site users can now log in, log out, change their password, and reset their password. However, we need to build a view to allow visitors to create a user account.

User registration

Let’s create a simple view to allow user registration on your website. Initially, you have to create a form to let the user enter a username, their real name, and a password.

Edit the forms.py file located inside the account application directory and add the following lines highlighted in bold:

from django import forms
from django.contrib.auth.models import User
class LoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)
class UserRegistrationForm(forms.ModelForm):
    password = forms.CharField(label='Password',
                               widget=forms.PasswordInput)
    password2 = forms.CharField(label='Repeat password',
                                widget=forms...

Building a custom authentication backend

Django allows you to authenticate users against different sources. The AUTHENTICATION_BACKENDS setting includes a list of authentication backends available in the project. The default value of this setting is the following:

['django.contrib.auth.backends.ModelBackend']

The default ModelBackend authenticates users against the database using the User model of django.contrib.auth. This is suitable for most web projects. However, you can create custom backends to authenticate your users against other sources, such as a Lightweight Directory Access Protocol (LDAP) directory or any other system.

You can read more information about customizing authentication at https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#other-authentication-sources.

Whenever the authenticate() function of django.contrib.auth is used, Django tries to authenticate the user against each of the backends defined in AUTHENTICATION_BACKENDS...

Additional resources

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

Summary

In this chapter, you learned how to build an authentication system for your site. You implemented all the necessary views for users to register, log in, log out, edit their password, and reset their password. You built a model for custom user profiles, and you created a custom authentication backend to let users log into your site using their email address.

In the next chapter, you will learn how to implement social authentication on your site using Python Social Auth. Users will be able to authenticate with their Google, Facebook, or Twitter accounts. You will also learn how to serve the development server over HTTPS using Django Extensions. You will customize the authentication pipeline to create user profiles automatically.

Join us on Discord

Read this book alongside other users and the author.

Ask questions, provide solutions to other readers, chat with the author via Ask Me Anything sessions, and much more. Scan the QR code or visit the link to join the book community.

https://packt.link/django

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é