Chapter 5. User Management

Django Allauth (2) – Installation and Initial Settings

Django Allauth (2) – Installation and Initial Settings
Tag:

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-2--Install-and-Initial-Settings

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-2--Install-and-Initial-Settings

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

Django-Allauth-2--Install-and-Initial-Settings

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.

Django-Allauth-2--Install-and-Initial-Settings

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.

Django-Allauth-2--Install-and-Initial-Settings

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.

Django-Allauth-2--Install-and-Initial-Settings

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.

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-2--Install-and-Initial-Settings

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-2--Install-and-Initial-Settings

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

Django-Allauth-2--Install-and-Initial-Settings

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.

Django-Allauth-2--Install-and-Initial-Settings

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.

Django-Allauth-2--Install-and-Initial-Settings

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.

Django-Allauth-2--Install-and-Initial-Settings

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.

Tag: