Answers for "django gmail login"

-1

django gmail login

$ pip install django-allauth

#settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        'APP_DIRS': True,
        #...
    }
]

INSTALLED_APPS = [
    #...
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google',
]

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend'
]

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': [
            'profile',
            'email',
        ],
        'AUTH_PARAMS': {
            'access_type': 'online', #set offline if you want background auth
        }
    }
}

SITE_ID = 2

LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'

#templates

{% load socialaccount %}
<html>
<body>
<h1>My Google OAuth Project </h1>
{% if user.is_authenticated %}
  <p>Welcome, You are logged in as {{ user.username }}</p>
{% else %}
  <a href="{% provider_login_url 'google' %}">Login With Google</a>
{% endif %}
</body>
</html>

#urls.py

from django.urls import path, include
from django.views.generic import TemplateView
from django.contrib.auth.views import LogoutView

urlpatterns = [
    #...
    path('', TemplateView.as_view(template_name="index.html")),
    path('accounts/', include('allauth.urls')),
    path('logout', LogoutView.as_view()),
]

#Register with Google Developer API
https://console.developers.google.com/apis
  
#Then, add:
http://127.0.0.1:8000 under Authorized JavaScript origins.
http://127.0.0.1:8000/accounts/google/login/callback/ under Authorized redirect URIs.

$ python manage.py migrate
$ python manage.py createsuperuser
$ python manage.py runserver
"""Open http://127.0.0.1:8000/admin and login to Django Admin. 
Under Sites click Add and put 127.0.0.1:8000 as both the Domain name and Display name.

Then, under Social Applications click Add and fill in the details as follows:

Provider: Google
Name: OAuth App
Client id: <The client ID you created in step 4>
Secret key: <The Secret key you created in step 4>
Sites: 127.0.0.1:8000
Since you are currently logged in as a superuser, 
logout and login again using your Google account.

If you get an error: SocialApp matching query does not exist at 
http://127.0.0.1:8000/accounts/google/login/,
it means that the ID of the site you created in Django admin is not 
the same as the one in settings.py. Consider playing around with the SITE_ID value.

After signing in with Google, you can check the user information obtained from Google at:
http://127.0.0.1:8000/admin/socialaccount/socialaccount/
"""
Posted by: Guest on September-17-2021

Python Answers by Framework

Browse Popular Code Answers by Language