Privacy policyContactsAbout siteOpinionsGitHubDonate
© EVILEG 2015-2018
Recommend hosting

Django - Tutorial 036. How to add authentication through social networks. VKontakte

django, Social

On the recommendation of users of the site began to add authentication through social networks to the site. The first such social network was VKontakte, as the most popular social network among users of my site.

Django itself has the necessary functionality to work with the OAuth 2.0 protocol, which could be used in the VKontakte API to authenticate users on third-party resources (and not only for authentication). But in this case I did not write my bicycle using bare OAuth support in Django, but found a very good battery, which is probably well known among developers of Django sites, which allowed to introduce authentication via VKontakte in just a couple of hours.

This battery is named Python Social Auth Django .

Let's take a step-by-step look at what we need to do to connect authentication via VKontakte to the site with Django

Step 1 - Installing of Python Social Auth Django

This is done by one command in your virtual environment through the utility pip

pip install social-auth-app-django

The documentation suggests configuring two versions of the ORM for the authentication system through social networks. This is the classical ORM of Django and ORM MongoEngine, but it turned out that the package required for MongoEngine is outdated and slightly incompatible with the latest versions of Django, it just does not work, even in the mongoengine developer documentation there is a call for help with the utility's support. Therefore, we will adjust only for the classical ORM.

Step 2 - Registering a battery on your site

We register the authentication application in INSTALLED_APPS


Step 3 - Database Migration

You will need to apply changes to the database structure, since this battery has its own tables to work with user authentication.

./ migrate

Next, we'll follow one more recommendation for configuring the database, if you, like me, use PostgreSQL. Namely...

When using PostgreSQL, it is recommended to use the built-in JSONB field to store the extracted extra data. To enable it, set the following:


Step 4 - Configuring authentication backends

Also write in

    'social_core.backends.vk.VKOAuth2',          # authentication backend via VKontakte
    'django.contrib.auth.backends.ModelBackend', # classic authentication backend, so that authentication works through a common username and password

Be sure to enable the classical authentication backend, otherwise you will lose the ability to log in through the login and password to the site.

Step 5 - Configuring the template engine

I have a year and a half of developing this site, the TEMPLATES setting has remained virtually untouched, but I added one line for this battery

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'social_django.context_processors.backends', # Добавил эту строку

Step 6 - Setting up the keys for VKontakte

Here is the setting of secret keys for VKontakte


To get them, you need to create an application in the developer's VKontakte toolkit and take the ID of your application and the secret key for it.

Register the application

We go into its settings and see everything that is needed

As a result, we assign the following settings to these variables:

SOCIAL_AUTH_VK_OAUTH2_SECRET = 'Защищённый ключ'

Step 7 - Connecting routes for authentication in

This is done in this way

urlpatterns = [
    path('', include('social_django.urls')),

Step 8 - Adding a link to a route

And now add a link to the route somewhere in the template to run authentication via VKontakte

<a href="/login/vk-oauth2"><img src="/static/lvk.png" class="avatar-3" data-toggle="tooltip" title="{% trans 'Login via VKontakte' %}"></a>

Step 9 - Configure redirect for authentication

This is an optional setting that specifies the URL for redirecting the user to your page after successful authentication. Leave the root of the site


There already will understand, as it is better for you to do

Step 10 - Requesting permissions to access the email

I have my own mail notification system on the site, so it's important for me to have access to the email user to notify him of new events on the resource, so we'll add a request to access the email.


For Django I recommend VDS-hosting TIMEWEB

  • #
  • July 14, 2018, 4:17 a.m.

Мне интересно что будет если в обеих сетях в авторизации одинаковый еmail. Не выведет ли ошибку ?

Не, не будет, в данной батарейке уже есть необходимый функционал по разрулированию этой проблемы. Аутентификации из разных социальных сетей будут сливаться на один аккаунт. Так что всё нормально должно быть.

В следующей статье будет описан этот момент. Опубликую статью в понедельник.
  • #
  • Aug. 7, 2018, 4:10 a.m.

интересно можно ли через эту батарейку получить данные на данные в вк(друзья, фото итд)

Там можно запросить доступ к тому или иному функционалу, а вот полное использование API, как я понимаю, потребует либо дописывания функционала, или использование ещё каких-нибудь батареек

Нашёл ошибку в вашем примере

какая именно? написали бы сразу ))


Only authorized users can post comments.
Please, Log in or Sign up
Jan. 17, 2019, 11:51 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Jan. 17, 2019, 11:49 a.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
Jan. 17, 2019, 11:13 a.m.

C++ - Тест 003. Условия и циклы

  • Result:28points,
  • Rating points-10
Last comments
Jan. 16, 2019, 8:06 a.m.

Заработало. Забыл model->select(); вписать.
Jan. 16, 2019, 8:02 a.m.

Всё равно пусто, хотя строка с данными в базу добавляется.
Jan. 16, 2019, 7:51 a.m.
Евгений Легоцкой

потому, что нужно сохранять информацию для всех остальных ролей и столбцов через вызов переопределённого метода. Да к тому же вы ещё и зациклили вызов метода data. QVariant MySqlTableModel:...
Jan. 16, 2019, 7:43 a.m.

Сделал вот так. В tableView ничего нет, кроме заголовка. QVariant MySqlTableModel::data(const QModelIndex &index, int role) const{ if (role == Qt::DisplayRole) { QTime ...
Now discuss on the forum
Jan. 18, 2019, 11:26 a.m.

Для Desktop делал так: void pause(int ms){ QTimer timer; timer.setInterval( qBound(1, ms, 3600000) ); timer.setSingleShot(true); QEventLoop loop; QObject::connect(&...
Jan. 17, 2019, 12:01 p.m.
Алексей Внуков

у меня просто есть отдельное поле с чекбоксамими какие колонки нужно отображать CheckBox { id: checkBox text: qsTr("some text") checked: true onC...
Jan. 15, 2019, 4:53 p.m.

Спасибо, заработало.Но выдало обычный текст без форатирования HTML.Придется искать дальше
Jan. 15, 2019, 12:52 p.m.

Я же вам выше написал CLion умеет работать с ремоут машинами. И Qt так же собирает.
Join us in social networks

For registered users on the site there is a minimum amount of advertising