django-allauth social account is already exitsts

1.3k views Asked by At

I have a user with connected to social account twitter. I registered new user and trying to connect twitter account is already exists. Exeption: The social account is already connected to a different account.

I used to:
<a href="{% provider_login_url "twitter" process="connect" next='/'%}"> connect Twitter acount</a><br>

How to catch this exception or redirect to another page if login failed?

Thank you.

1

There are 1 answers

0
user1667957 On

I think is completed.

add into settings.py

  SOCIALACCOUNT_ADAPTER = 'adapter.SocialAccountAdapter'

create

#project/settings/adapter.py
from django.contrib.auth.models import User
from django.shortcuts import HttpResponse,redirect
from allauth.account.models import EmailAddress
from allauth.exceptions import ImmediateHttpResponse
from allauth.socialaccount.signals import pre_social_login
from allauth.account.utils import perform_login
from django.dispatch import receiver
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter  

class SocialAccountAdapter(DefaultSocialAccountAdapter):
    def pre_social_login(self, request, sociallogin):
            pass

@receiver(pre_social_login)
def link_to_local_user(sender, request, sociallogin, **kwargs):
        try:
            user = User.objects.get(email=sociallogin.account.user.email)
            if user:
                perform_login(request, user, email_verification='optional')
                raise ImmediateHttpResponse(redirect('/your/url/'))
        except User.DoesNotExist:
            user = User.objects.get(id=request.user.id)
            sociallogin.connect(request, user)`