In this tutorial, we will build a Django application that allow users to sign in via their GitHub account.
Sample Project
$ mkdir django-github-authentication && cd django-github-authentication
$ pipenv install django django-allauth
$ pipenv shell
$ django-admin startproject config .
$ python manage.py startapp posts
from django.urls import reverse_lazy
INSTALLED_APPS = [
...
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.github',
'posts.apps.PostsConfig',
]
TEMPLATES = [
{
...
'DIRS': [BASE_DIR, 'templates'],
...
},
]
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend",
)
ACCOUNT_EMAIL_VERIFICATION = 'none'
LOGIN_REDIRECT_URL = reverse_lazy('posts:post-list')
SITE_ID = 1
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
def __str__(self):
return self.title
$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py shell
>>> from posts.models import Post
>>> Post.objects.create(title='My First Post', content='My First Content')
>>> Post.objects.create(title='My Second Post', content='My Second Content')
from django.views.generic import ListView
from .models import Post
class PostListView(ListView):
model = Post
context_object_name = 'posts'
➜ tree .
.
├── Pipfile
├── Pipfile.lock
├── config
│ ├── __init__.py
│ ├── asgi.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── db.sqlite3
├── manage.py
├── posts
│ ├── __init__.py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations
│ │ ├── 0001_initial.py
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ ├── urls.py
│ └── views.py
└── templates
└── posts
└── post_list.html
{% load socialaccount %}
{% load account %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% if user.is_authenticated %}
Hi: {% user_display user %}
{% for post in posts %}
{{ post.title }}
{{ post.content }}
{% endfor %}
{% else %}
<p>Please <a href="{% provider_login_url 'github' %}">Authenticate with GitHub</a></p>
{% endif %}
</body>
</html>
This is only for test purpose, we want to see that our GitHub authentication works.
from django.urls import path
from .views import PostListView
app_name = 'posts'
urlpatterns = [
path('', PostListView.as_view(), name='post-list'),
]
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')),
path('posts/', include('posts.urls'))
]
$ python manage.py createsuperuser
Share this: