django中集成第三方登录github

2024年4月29日 18:03 by wst

django

安装步骤

现在时间:2024-04-29 15:51:51 python=3.10.14

 

  1. 安装环境: conda create -n dtest python=3.10
  2. 安装Django(默认为最新版本5.0.4):pip install django
  3. 安装重要组件(默认最新版本0.62.1):pip install django-allauth

操作步骤

  1. 创建项目: django-admin startproject django_blog

此时目录结构:

.
├── django_blog
│   ├── asgi.py
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py

  1. 配置django_blog/settings.py
django_blog/settings.py

...
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
    "allauth.account.middleware.AccountMiddleware"
]

TEMPLATES = [
    {
        ...
        'OPTIONS': {
            'context_processors': [
                # allauth 启动必须项
                'django.template.context_processors.request',
            ],
        },
    },
]


AUTHENTICATION_BACKENDS = (
    # Django 后台可独立于 allauth 登录
    'django.contrib.auth.backends.ModelBackend',

    # 配置 allauth 独有的认证方法,如 email 登录
    'allauth.account.auth_backends.AuthenticationBackend',
)


INSTALLED_APPS = [
    ...
    # allauth 启动必须项
    'django.contrib.auth',
    'django.contrib.messages',
    'django.contrib.sites',

    'allauth',
    'allauth.account',
    'allauth.socialaccount',

    # 可添加需要的第三方登录
    'allauth.socialaccount.providers.github',
    'allauth.socialaccount.providers.weibo',
    ...
]

# 设置站点
SITE_ID = 1

# 登录成功后重定向地址
LOGIN_REDIRECT_URL = '/'

...
  1. 给django-allauth分配url,文件django_blog/urls.py
django_blog/urls.py

...

urlpatterns = [
    ...
    path('accounts/', include('allauth.urls')),
    ...
]
  1. 迁移数据库
python manage.py migrate
  1. 启动服务:python manage.py runserver

  2. 访问默认登录页:http://127.0.0.1:8000/accounts/login/

配置首页

  1. 创建文章app
python manage.py startapp article
  1. 添加到settings.py的installs_app中:
# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'article',
    # 可添加需要的第三方登录
    'allauth.socialaccount.providers.github',
]
  1. 设置模板目录(django_blog/settings.py):
import os
TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [os.path.join(BASE_DIR, 'templates')],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
                'django.template.context_processors.request',
            ],
        },
    },
]
  1. 编写首页模板(templates/article/home.html):
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>欢迎来到我的博客网站!</h1>
    <a href="/accounts/login">登录</a>
</body>
</html>
  1. 编写views(article/views.py):
from django.shortcuts import render

# Create your views here.

def home(request):
    "首页"
    return render(request, "article/home.html")
  1. 配置首页地址(django_blog/urls.py):
from django.contrib import admin
from django.urls import path, include
from article.views import home

urlpatterns = [
    path("admin/", admin.site.urls),
    path('accounts/', include('allauth.urls')),
    path('', home, name='home'),

]

7. 再次访问(http://127.0.0.1:8000/)可看到首页:

美化页面

django-allauth自带的模板是简陋的,需要覆写为自己网站的风格才能使用。

  1. 复制安装目录的这个文件(site-packages/allauth/templates/account/base_entrance.html)到(templates/account/base.html)

  2. 创建html文件(templates/account/login.html)同时引入bootstrap4的样式文件:

templates/account/login.html



{% extends "account/base.html" %}
{% load i18n %}
{% load account socialaccount %}
{% block title %}登录{% endblock %}

{% block extra_head %}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
{% endblock%}

{% block content %}
<div class="container">
    <div class="row">
        <div class="col-12">
            <br>
            {% get_providers as socialaccount_providers %}
            {% if socialaccount_providers %}
            <p>
                {% blocktrans with site.name as site_name %}请登录已有本地账号或<a href="{{ signup_url }}">注册</a>新账号。
                也可以通过第三方登录:{% endblocktrans %}
            </p>

            <div class="socialaccount_ballot">
                <h5 class="mb-2 mt-4">第三方登录:</h5>
                <ul class="socialaccount_providers">
                  {% include "socialaccount/snippets/provider_list.html" with process="login" %}
                </ul>
                <h5 class="mb-2 mt-4">本地登录:</h5>
            </div>

            {% include "socialaccount/snippets/login_extra.html" %}

            {% else %}
            <p>{% blocktrans %}If you have not created an account yet, then please
            <a href="{{ signup_url }}">sign up</a> first.{% endblocktrans %}</p>
            {% endif %}
            <div class="col-6">
                <form class="login" id="login_form" method="POST" action="{% url 'account_login' %}">
                    {% csrf_token %}
                    <div class="form-group">
                        <label for="id_login">账号: </label>
                        <input type="text" name="login" placeholder="请输入用户名或Email" autofocus="autofocus" required
                            id="id_login" class="form-control" />
                        <small class="form-text text-muted ml-1">
                            还没有账号?
                            <a href="{% url 'account_signup' %}" style="color: cornflowerblue; ">
                                注册新账号
                            </a>
                        </small>
                    </div>
                    <div class="form-group mb-1">
                        <label for="id_password">
                            密码:
                        </label>
                        <input type="password" name="password" placeholder="请输入密码" required id="id_password"
                            class="form-control" />
                        <small class="form-text text-muted ml-1">
                            <a class="secondaryAction layui-text" href="{% url 'account_reset_password' %}">
                                忘记密码?
                            </a>
                        </small>
                    </div>
                    <div class="custom-control custom-checkbox mb-2">
                        <input type="checkbox" name="remember" id="id_remember" checked class="custom-control-input" />
                        <label for="id_remember" class="custom-control-label">
                            保持登录
                        </label>
                    </div>
                    <button class="primaryAction btn btn-primary" type="submit" id="submit_login">确认</button>
                </form>
            </div>
        </div>
    </div>
</div>
{% endblock %}
  1. 再次访问登录页面,发现好看点了。暂时还看不到第三方登录选项,配置后才能看到。

创建超级用户

python manage.py createsuperuser

根据提示输入用户名和密码

配置第三方登录

请先到GitHub哪里申请个应用,配置大概如下:

  1. 为了给用户发邮件,请把如下配置添加到settings.py中:
# SMTP服务器
EMAIL_HOST = 'your smtp'
# 邮箱名
EMAIL_HOST_USER = 'your email'
# 邮箱密码
EMAIL_HOST_PASSWORD = 'your password'
# 发送邮件的端口
EMAIL_PORT = 25
# 是否使用 TLS
EMAIL_USE_TLS = True
# 默认的发件人
DEFAULT_FROM_EMAIL = 'your email'
  1. 进入管理端页面:http://127.0.0.1:8000/admin/
    在Sites下面,把已有的那条记录改为你的本地网址,Domain name和Display name都设置为:http://127.0.0.1:8000,然后点击SAVE.

  2. 再点击Social applications, 添加一条记录,name随便填,Client id:和Secret key:填写你在GitHub哪里的申请的。然后把页面下边sites中的记录从左边移动到右边。然后点击SAVE.

  3. 以上操作完之后,点击退出。

  4. 再次进入登录页(http://127.0.0.1:8000/accounts/login/
    此时可以看到github登录选项。

  5. 点击第三方登录中的GitHub,即可实现第三方登录。

如果有老铁遇到问题,可在这里索取源码:

关注公众号,回复django_blog. 


Comments(0) Add Your Comment

Not Comment!