Menu

Log in

Sign up

From beginner to master of web design, coding, infrastructure operation, business development and marketing

  • COURSES
  • HTML & CSS Introduction
  • HTML & CSS Coding with AI
  • Linux Introduction
  • Docker Basics
  • Git & GitHub Introduction
  • JavaScript Coding with AI
  • Django Introduction
  • AWS Basics
  • Figma Introduction
  • SEO Tutorial for Beginners
  • SEO with AI
  • OTHERS
  • About
  • Terms of Service
  • Privacy Policy

© 2024 D-Libro. All Rights Reserved

Django IntroductionChapter 5. User Management

Django Allauth (2) – Installation and Initial Settings

Django Allauth (2) – Installation and Initial Settings

Setting Up Django Allauth: Installation and Initial Settings

The first steps to using django-allauth are installing it and adding initial settings. In this chapter, we continue to use the employee learning app to demonstrate django-allauth settings and functionalities.

1. Install django-allauth

To install django-allauth, add it to requirements.txt.

requirements.txt
Django==4.1.7
django-crispy-forms
crispy-bootstrap5
django-allauth

Run the command below to install django-allauth.

Command Line - INPUT
pip install -r requirements.txt

Check the project directory tree. You can find that the allauth directory is created under d_env/lib/python3.xx/site-packages like in the image below.

Django Allauth directory structure

The important file and directory are:

  • The urls.py file under the account directory
  • The templates directory located immediately under the allauth directory

The urls.py contains urlpatterns for user authentications. The templates directory contains many HTML templates that are used for user authentication UIs.

2. Edit settings.py

Add apps

The following apps are required according to the official document. Some apps are already registered. Add the ones in yellow.

config/settings.py
INSTALLED_APPS = [
      :
    'test_app',
    'employee_learning',
    'crispy_forms',
    'crispy_bootstrap5',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
]

Add Site ID and Authentication Backends

Add the code below at the end of settings.py. To make the section in the settings.py file clear, you can add ### django-allauth settings### in the beginning. The comments in green are the comments from the official documentation. The comments explain why we need these settings.

config/settings.py
### django-allauth settings ###

SITE_ID = 1

AUTHENTICATION_BACKENDS = [
  # Needed to login by username in Django admin, regardless of `allauth`
    'django.contrib.auth.backends.ModelBackend',
  # `allauth` specific authentication methods, such as login by e-mail
    'allauth.account.auth_backends.AuthenticationBackend',
]

Login and logout redirection settings

Add the code below at the end. This code is used to set redirection URLs used for login and logout. We set the landing page for the login redirect URL and the login page for the logout redirect URL.

For now, comment out the ACCOUNT_LOGOUT_ON_GET = True part. This part will be explained later.

config/settings.py
 'allauth.account.auth_backends.AuthenticationBackend',
]

# LOGIN and LOGUT Redirection
LOGIN_REDIRECT_URL ='/'
ACCOUNT_LOGOUT_REDIRECT_URL ='/accounts/login/'
# ACCOUNT_LOGOUT_ON_GET = True

Change account authentication method to email

Lastly, add the code below. In this example, we'll use the email authentication approach, which has been recently more common than the username authentication approach. But for email verification, set it as "none" for now. We'll cover email verification settings later in this chapter.

config/settings.py
ACCOUNT_LOGOUT_REDIRECT_URL ='/accounts/login/'
# ACCOUNT_LOGOUT_ON_GET = True

ACCOUNT_AUTHENTICATION_METHOD = "email"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "none"

ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_UNIQUE_USERNAME = False

#Add the following when you are using custom user model
#ACCOUNT_USER_MODEL_USERNAME_FIELD = None

3. Edit urls.py

As you need to connect between the main urls.py and the urls.py under allauth directory, add a new path in the main urls.py shown below.

config/urls.py
urlpatterns = [
      :
    path('accounts/', include('allauth.urls')),
]

The urls.py under the allauth directory is linked with another urls.py file under the account directory.

The urls.py file under the account directory contains the following urlpatterns. This list is important to understand how to check URLs and URL names used for user authentication pages. This is only for your reference. There is no need to edit this file.

allauth/account/urls.py
urlpatterns = [
    path("signup/", views.signup, name="account_signup"),
    path("login/", views.login, name="account_login"),
    path("logout/", views.logout, name="account_logout"),
    path("password/change/", views.password_change, name="account_change_password",),
    path("password/set/", views.password_set, name="account_set_password"),
    path("inactive/", views.account_inactive, name="account_inactive"),
# E-mail
    path("email/", views.email, name="account_email"),
    path("confirm-email/", views.email_verification_sent, name="account_email_verification_sent",),
    re_path(r"^confirm-email/(?P[-:\w]+)/$", views.confirm_email, name="account_confirm_email",),
# password reset
    path("password/reset/", views.password_reset, name="account_reset_password"),
    path("password/reset/done/", views.password_reset_done, name="account_reset_password_done",),
    re_path(r"^password/reset/key/(?P[0-9A-Za-z]+)-(?P.+)/$", views.password_reset_from_key, name="account_reset_password_from_key",),
    path("password/reset/key/done/", views.password_reset_from_key_done, name="account_reset_password_from_key_done",),
]

4. Run the migrate command

As migration files are already prepared, you just run the migrate command.

Command Line - INPUT
python manage.py migrate
Command Line - RESPONSE
Operations to perform:
  Apply all migrations: account, admin, auth, contenttypes, employee_learning, sessions, sites, socialaccount, test_app
Running migrations:
  Applying account.0001_initial... OK
  Applying account.0002_email_max_length... OK
  Applying sites.0001_initial... OK
  Applying sites.0002_alter_domain_unique... OK
  Applying socialaccount.0001_initial... OK
  Applying socialaccount.0002_token_max_lengths... OK
  Applying socialaccount.0003_extra_data_default_dict... OK

5. Check the results

To check if the initial settings are appropriately done, execute the runserver command.

Command Line - INPUT
python manage.py runserver

The user authentication pages are available at the URL written in the urls.py file udder allauth/account. Check one of the URLs, for example, http://localhost:8000/accounts/login/. Although UIs do not look good, you can access the key pages for user authentications now.

Django Allauth Sign In Page UI

Try to sign in. You will be directed to the home page if you can successfully sign in.

Index page UI example (After login)

Although you cannot see the login status, you are logged in to the app now. In this status, if you try to go to http://localhost:8000/accounts/login/ again, you'll be redirected to the home page as it is set as a login redirect URL. If you want to log out, you need to type http://localhost:8000/accounts/logout/.

Continuing to type URLs is not efficient during the development process. Add links to Signup, Login, and Logout as a temporary solution in the navbar by editing the base.html file. Add the yellow part below. The URL names are picked from the urls.py file under allauth/account.

templates/base.html
<div class="collapse navbar-collapse" id="navbarNav">
  <ul class="navbar-nav">
    <li class="nav-item">
      <a class="nav-link" href="{% url 'course_list'%}">List</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="{% url 'course_create'%}">Create</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="{% url 'account_signup'%}">Signup</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="{% url 'account_login'%}">Login</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="{% url 'account_logout'%}">Logout</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="{% url 'account_change_password'%}">Change Password</a>
    </li>
  </ul>
</div>

After saving the file, refresh the browser. You can now have access to the Logout page. Also, you can check that you cannot go to the Signup and Login page when you are in the login status.

Index page UI example with a modified navbar

When you try to go to some pages, you may encounter the error like the one below. This is because we haven't done email-related settings, which will be explained in the next section.

Connection Error message

IdeaNote: Account Logout On Get

In the Login and Logout redirection settings, we commented out the "ACCOUNT_LOGOUT_ON_GET = True" part. This setting is used to set the logout steps. If this is set as "True", the user is immediately logged out when they click on the link to the logout page.

How Account Logout On Get works

The default setting is "False". Thus, when this setting is commented out, you still go to the Logout page when clicking on the logout link. To change the setting, take out # like shown below.

config/settings.py
# LOGIN and LOGUT Redirection
LOGIN_REDIRECT_URL ='/employee-learning/course-list/'
ACCOUNT_LOGOUT_REDIRECT_URL ='/accounts/login/'
ACCOUNT_LOGOUT_ON_GET = True

Refresh the browser and click on the logout link. You'll be immediately logged out.


You can also learn this topic offline. Click AmazonKindle.

More Topics to Explore

Configuring Email with SendGrid for Django

Email Setting – SendGrid

Configuring Email with SendGrid for Django

Email Setting – SendGrid

Tags:

requirements.txt

User Authentication

User Management

django-allauth

Django Library

Django Introduction
Course Content

Chapter 1. Django Key Concepts

Web Framework and Django

Websites vs. Django Web Apps

How Django Handles HTTP Request and HTTP Response

Django's MVT Framework

Django Templates vs. Django APIs

Chapter 2. Django Quick Start Guide

Install Python

Install Visual Studio Code

Create Project Directory

Set Up Virtual Environment

Install Django

Start Django Project

Run Server

Database Migration

URL dispatcher – urls.py

Create Superuser and Log In to Django Admin

Start App

Create HTML Templates

Create Views

Add URL Patterns

Project vs. App

Chapter 3. Django Models and Databases

Create a Database in Django

Relational Database

Create Django Models

Makemigrations and Migrate

Add Models in Django Admin – admin.py

Change Display Name of Record Objects

Django Models – Data Field Type

Django Models – Field Options

Django Models – Help Text Option

Django Models – Choices Option

Django Models – DateField with datetime Module

Django Models – Relationship Fields

Django Models – ID

Django Models – ForeignKey (OneToMany Relationship)

Django Models – OneToOneField

Django Models – ManyToManyField

Chapter 4. Create CRUD Web Application

CRUD Web Application

Basic CRUD Structure in Django

Django Generic Views

How To Write Class-Based Views with Generic Views

Generic View Basic Attributes

URL Dispatcher for CRUD Views

Django Templates for CRUD Views

Django Template Language (DTL)

Template for List Page

get_FOO_display method

Template for Detail Page

Template with Model Relations

Template for Create and Update Page

Template for Delete Page

Add Links – {% url %} tag

Extend Templates – {% extends %} tag

Check Developing App UI on Mobile Device

Django Templates with Bootstrap

Crispy Forms

Customize Views (1) – Change List Order

Customizing Views (2) – Filter Lists

Context

Customize Views (3) – Add Extra Context

Modularize Templates – {% include %} tag

Static Files in Development Environment – {% static %} tag

STATIC_URL and STATICFILES_DIRS

Create Index HTML

Chapter 5. User Management

User Authentication

Overview of User Management Functions

User Management Function Development with Django

Approaches to Building User Management Functions in Django

Django Allauth (1) – Introduction

Django Allauth (2) – Installation and Initial Settings

Django Allauth (3) – Email Verification via Console

Django Allauth (4) – Email Verification via Gmail

Django Allauth (5) – Social Login with GitHub

Django Allauth (6) – Social Login with Google

Django Allauth (7) – Allauth Template File Setup

Django Allauth (8) – Add Basic Styling with Bootstrap and Crispy Forms

Django Allauth (9) – Customize Sign-in and Sign-up Pages

User Models

Login Required – LoginRequiredMixin

User Login Status Icon on Navigation Bar

Chapter 6. Deploy Django App

Overview of Django App Deployment (1)

Overview of Django App Deployment (2)

Key Steps of Django App Deployment

Hosting Service Initial Settings (1) – AWS Lightsail setup

Hosting Service Initial Settings (2) – SSH Remote Connection

Manage Local Computer and Remote Server Simultaneously

Tips for Managing Local Development and Remote Production Environment

Hosting Service Initial Settings (3) – Clone Project Directory with GitHub

Production Database Setup

Django Production Settings (1) – Settings.py for Development and Production

Django Production Settings (2) – Production Settings

Django Production Settings (3) – django-environ and .env file

Static File Settings

Django and Dependency Installation on Production Server

Web Server and Application Server in Django

Application Server Setup – Gunicorn

Web Server Setup – Nginx

Domain Setup

SSL Setup – Certbot

Email Setting – SendGrid

Social Login for Production

Manage Local Development and Remote Production Environment

Chapter 1. Django Key Concepts

Web Framework and Django

Websites vs. Django Web Apps

How Django Handles HTTP Request and HTTP Response

Django's MVT Framework

Django Templates vs. Django APIs

Chapter 2. Django Quick Start Guide

Install Python

Install Visual Studio Code

Create Project Directory

Set Up Virtual Environment

Install Django

Start Django Project

Run Server

Database Migration

URL dispatcher – urls.py

Create Superuser and Log In to Django Admin

Start App

Create HTML Templates

Create Views

Add URL Patterns

Project vs. App

Chapter 3. Django Models and Databases

Create a Database in Django

Relational Database

Create Django Models

Makemigrations and Migrate

Add Models in Django Admin – admin.py

Change Display Name of Record Objects

Django Models – Data Field Type

Django Models – Field Options

Django Models – Help Text Option

Django Models – Choices Option

Django Models – DateField with datetime Module

Django Models – Relationship Fields

Django Models – ID

Django Models – ForeignKey (OneToMany Relationship)

Django Models – OneToOneField

Django Models – ManyToManyField

Chapter 4. Create CRUD Web Application

CRUD Web Application

Basic CRUD Structure in Django

Django Generic Views

How To Write Class-Based Views with Generic Views

Generic View Basic Attributes

URL Dispatcher for CRUD Views

Django Templates for CRUD Views

Django Template Language (DTL)

Template for List Page

get_FOO_display method

Template for Detail Page

Template with Model Relations

Template for Create and Update Page

Template for Delete Page

Add Links – {% url %} tag

Extend Templates – {% extends %} tag

Check Developing App UI on Mobile Device

Django Templates with Bootstrap

Crispy Forms

Customize Views (1) – Change List Order

Customizing Views (2) – Filter Lists

Context

Customize Views (3) – Add Extra Context

Modularize Templates – {% include %} tag

Static Files in Development Environment – {% static %} tag

STATIC_URL and STATICFILES_DIRS

Create Index HTML

Chapter 5. User Management

User Authentication

Overview of User Management Functions

User Management Function Development with Django

Approaches to Building User Management Functions in Django

Django Allauth (1) – Introduction

Django Allauth (2) – Installation and Initial Settings

Django Allauth (3) – Email Verification via Console

Django Allauth (4) – Email Verification via Gmail

Django Allauth (5) – Social Login with GitHub

Django Allauth (6) – Social Login with Google

Django Allauth (7) – Allauth Template File Setup

Django Allauth (8) – Add Basic Styling with Bootstrap and Crispy Forms

Django Allauth (9) – Customize Sign-in and Sign-up Pages

User Models

Login Required – LoginRequiredMixin

User Login Status Icon on Navigation Bar

Chapter 6. Deploy Django App

Overview of Django App Deployment (1)

Overview of Django App Deployment (2)

Key Steps of Django App Deployment

Hosting Service Initial Settings (1) – AWS Lightsail setup

Hosting Service Initial Settings (2) – SSH Remote Connection

Manage Local Computer and Remote Server Simultaneously

Tips for Managing Local Development and Remote Production Environment

Hosting Service Initial Settings (3) – Clone Project Directory with GitHub

Production Database Setup

Django Production Settings (1) – Settings.py for Development and Production

Django Production Settings (2) – Production Settings

Django Production Settings (3) – django-environ and .env file

Static File Settings

Django and Dependency Installation on Production Server

Web Server and Application Server in Django

Application Server Setup – Gunicorn

Web Server Setup – Nginx

Domain Setup

SSL Setup – Certbot

Email Setting – SendGrid

Social Login for Production

Manage Local Development and Remote Production Environment