I came to peace with methodically reading the documentation, but you might’ve not. I’ll do it for you. I want it all to work and I only want to write it down once. Buckle up.
Part 1 is about Installation and Facebook Login. Check out the whole series Django-allauth.
Other parts will be about profiles and all kinds of forms and user interractions.
Table of Contents:
Interlude
After following Vitor’s tutorial on local user login and felt empowered to try and get a grasp on full on user login with everything you might need. I looked into Vitor’s guide for social-auth-app-django, but the package hasn’t been updated in two years and at this date has 84 open issues, so I had to turn to django-allauth.
Extended User Model
I will be using a custom AbstractUser model, I talked about it here. Don’t forget to set AUTH_USER_MODEL = 'yourapp.CustomUser'
in the settings.py
.
1. Installation
These are things from the official docs.
If your environment, install the package:
pip install django-allauth
Modern installation order replicates some of the existing ones, except for that you don’t need to include allauth
processors in your TEMPLATE['OPTIONS']['context_processors']
. That is:
You INSTALLED_APPS should have these apps included:
'django.contrib.auth',
'django.contrib.messages',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
# selected providers, more at https://django-allauth.readthedocs.io/en/latest/installation.html
'allauth.socialaccount.providers.vk', # if you need VK api
'allauth.socialaccount.providers.facebook', # if you need FB api
Your settings must also have:
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',
)
SITE_ID = 1
If you want social login, add:
# Provider specific settings
SOCIALACCOUNT_PROVIDERS = {
'google': {
# For each OAuth based provider, either add a ``SocialApp``
# (``socialaccount`` app) containing the required client
# credentials, or list them here:
'APP': {
'client_id': '123',
'secret': '456',
'key': ''
}
}
}
And your urls.py
:
urlpatterns = [
url(r'^accounts/', include('allauth.urls')),
]
Configuration
Going through the configuration page, this is my opinion on the parameters:
ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = False # a personal preference. True by default. I don't want users to be interrupted by logging in
ACCOUNT_AUTHENTICATION_METHOD = 'email' # a personal preference. I don't want to add 'i don't remember my username' like they did at Nintendo, it's stupid
will be used for login
ACCOUNT_LOGIN_ON_PASSWORD_RESET = True # False by default
ACCOUNT_LOGOUT_ON_PASSWORD_CHANGE = True # True by default
# ACCOUNT_LOGOUT_REDIRECT_URL = '/login'
ACCOUNT_USERNAME_BLACKLIST = ['suka', 'blyat',] # :D
ACCOUNT_USERNAME_MIN_LENGTH = 4 # a personal preference
ACCOUNT_SESSION_REMEMBER = True # None by default (to ask 'Remember me?'). I want the user to be always logged in
Errors at this stage
Most are fixed my running migrate
, others I didn’t encounter. I can help you in the comments!
2. Simple Social Signup
Make a template anywhere you want with this content:
{% load socialaccount %}
{% if user.is_authenticated %}
Hello, {{ user.username }}. <a href='/logout'>Logout</a>
{% else %}
<a href="{% provider_login_url 'facebook' %}">Login or Sign Up</a>
{% endif %}
Errors at this stage
Error: Site matching query does not exist.
Something must be wrong with SITE_ID. If it is not in your settings.py, set it SIDE_ID=1
or if it doesn’t work, investigate it, maybe create one (via shell
):
from django.contrib.sites.models import Site
Site.objects.create(name='127.0.0.1:8000', domain='127.0.0.1:8000')
If that doesn’t work, idk, set it to SITE_ID=2
.
Error: SocialApp matching query does not exist.
It means you haven’t set your social credentials. Say, you make a template with {% provider_login_url 'facebook' %}
even though you didn’t set up connection Facebook, oops. If you did, then go to /admin/socialaccount/socialapp/
and create a SocialApp instance. If not, follow instructions bellow.
3. Connecting to Facebook
Interlude
When I first set up Facebook login a few years ago, it was a walk in the park. I followed Vitor’s guide and it went fine. When I returned to it around a year ago, it didn’t work. Developer corner’s interface changed, some others things did too, and it discouraged me a lot. Especially knowing that Facebook login is much easier to set up than VK admin (and it is an essential one for every post-soviet website).
Step by step (August, 2020)
Go to developers.facebook.com, click My apps and create a new one.
Choose ‘For Everything Use‘:

Display name can be anything, it doesn’t matter.

Then confirm you are human, if not – 01001000 01100101 01101100 01101100 01101111 00100001
Click Facebook Login.

Then pick Web. For Site Url set http://localhost:8000
(it doesn’t accept http://127.0.0.1:8000
), Save and Continue.
Go to Settings – Basic and set up things.

And set a few things:


Then you need to set Social App. Either do it at /admin/socialaccount/socialapp/
:

SOCIALACCOUNT_PROVIDERS = {
'facebook':
'facebook':
{
'METHOD': 'oauth2',
'SDK_URL': '//connect.facebook.net/{locale}/sdk.js',
'SCOPE': ['email', 'public_profile'],
'AUTH_PARAMS': {'auth_type': 'reauthenticate'},
'INIT_PARAMS': {'cookie': True},
'FIELDS': [
'id',
'first_name',
'last_name',
'name',
'name_format',
'picture',
'short_name'
],
'EXCHANGE_TOKEN': True,
'LOCALE_FUNC': lambda request: 'ru_RU',
'VERIFIED_EMAIL': False,
'VERSION': 'v7.0',
# you should fill in 'APP' only if you don't create a Facebook instance at /admin/socialaccount/socialapp/
'APP': {
'client_id': 'App ID', # !!! THIS App ID
'secret': 'App Secret', # !!! THIS App Secret
'key': ''
}
}
}
Find more about VERSION
of Facebook Graph API.
WARNING! Parameters in settings.py
file have higher priority than those in /admin/socialaccount/socialapp/
. So those in settings.py
will be used if they are provided, otherwise – the SocialApp
instance.
By the way! You will need to make your base.html
work for accounts templates. For example, if your base.html does not contain {% block content %}
, you will get something like this – a skeleton.
A small advice – like you name opening block
as {% block content %}
, do the same for endblock
– {% endblock content %}
, don’t leave them at {% endblock %}
:
{% block content %} Not a good practice. {% endblock %}
{% block content %} A good practice. {% endblock content %}
It is a good practice and helps avoiding errors as templates can be really messy even without your interference.

Errors at this stage
RelatedObjectDoesNotExist at /accounts/social/signup.
But I couldn’t make it work solely with settings.py
as I got this error 😦

It somehow has to be able to create SocialApp instance for Facebook with the data I passed, but it didn’t.
There are two options to METHOD
– oauth2
and js_sdk
. For js_sdk
you will need to change template like this. You need to add method=”oauth2″ to the link.
{% extends 'base.html' %}
{% load socialaccount %}
{% providers_media_js %}
{% load socialaccount %}
{% block content %}
<body>
{% if user.is_authenticated %}
Hello, {{ user.username }}. <a href='/logout'>Logout</a>
{% else %}
<p><a href="{% provider_login_url 'facebook' method="js_sdk" %}">Facebook</a></p> # This with JS SDK
<p><a href="{% provider_login_url "facebook" method="oauth2" %}">Facebook OAuth2</a></p> # Or this with OAuth2
{% endif %}
</body>
{% endblock content %}
If you want to use method="js_sdk"
, you need to know, that it doesn’t work right off the bat. There is a useful reply on StackOverFlow telling how it is done using Facebook API and Javascript, I am yet to understand how to work it out with django-all-auth
.
The main reason why you would want to use JS SDK is that you don’t have to leave your website to login. As a compromise, I offer to add target="blank"
to the <a>
:
...
<p><a href="{% provider_login_url "facebook" method="oauth2" %}" target="blank">Facebook OAuth2</a></p> # Or this with OAuth2
...
As a result, Facebook Login will be opened in just a small window.
Email/Username already used
And now that I started this hustle with django-allauth
. The next step would be setting E-Mail
and username
. If you try to use the same email I have already used before and the form says that I can’t do that:

Facebook has detected MyAPP isn’t using a secure connection to transfer information.
If you are used to working with 127.0.0.1:8000
, you won’t be able to test Facebook login locally.

Use localhost:8000
to test this, you will find that it miraculously worked. I mean, literally just go to localhost:8000
and do your thing:

4. Login
Let’s talk about main links you will operate with.
url | description |
/accounts/signup | Signup page |
/accounts/login | Login |
/accounts/logout | Logout |
/accounts/social | Manage connections to social accounts |
/accounts/facebook/login | Login/Signup via Facebook |
Go to /accounts/login and press Facebook.
Errors at this stage
Facebook: Sorry, something went wrong. We’re working on getting this fixed as soon as we can.
When you press ‘Facebook’ at /accounts/login, it can show this error to you:

When you hover over that Facebook line:

You may see at the bottom of your browser window you can see the content of the <a href="link">
. Now listen, if in your settings.py
you used this great line (or something like that; I saw it a life ago somewhere):
TEMPLATES = [
{
#something something
'OPTIONS': {
'string_if_invalid': 'INVALID EXPRESSION: %s', # this line
},
},
]
Then hovering over Facebook
you will see this:

Basically you don’t provide variables scope and auth_params
, so this automatically generated page by django_all_auth
and that line in Templates create this monstrosity.
It helps a lot during development, but in this particular situation it will hinder it all. So comment that like out and refresh. You will seee a correct link:

5. For Live server
That was for localhost. Change a few things to make it work on Live.
- Switch In development to Live


2. Set Valid OAuth Redirect URIs in Facebook Login -> Settings.
3. Set HTTPS. For free SSL, use Certbot. Let’s Encrypt doesn’t support wildcard (no https for subdomains, like metrika in metrika.yandex.ru). There is a simple instruction on any kind of VPS, check it out.

3. Change Domain to your 🙂
Next time I will customize Email Confirmation as well as other templates and forms. Stay tuned!
[…] Part 1 was about Installation and Facebook Login. […]
LikeLike
[…] say choose localhost:8000 instead of 127.0.0.1:8000 – it was crucial for FaceBook Login (proof 1 and proof […]
LikeLike
[…] wrote about it previously, so please go check out pieces for Facebook and Google. Some things change all the time, but the main points still […]
LikeLike
only from my pc i can login to both gmail and facebook from other pc cannot login showing error like
Warning
URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.
LikeLike