All Projects → twtrubiks → django_social_login_tutorial

twtrubiks / django_social_login_tutorial

Licence: MIT license
Django Social Login Tutorial

Programming Languages

python
139335 projects - #7 most used programming language
HTML
75241 projects
CSS
56736 projects

Projects that are alternatives of or similar to django social login tutorial

bdapis
Rest API service. Build with NodeJS, Express, MongoDB
Stars: ✭ 65 (+0%)
Mutual labels:  heroku
bad-cards-game
Bad Cards Game
Stars: ✭ 23 (-64.62%)
Mutual labels:  heroku
events-manager-io
A basic site for managing event centers and scheduling events.
Stars: ✭ 19 (-70.77%)
Mutual labels:  heroku
SendEmail
C#邮件批量发送 支持mac/linux
Stars: ✭ 15 (-76.92%)
Mutual labels:  send-email
nativescript-auth0
Nativescript Auth0 https://auth0.com/ social authentication plugin
Stars: ✭ 57 (-12.31%)
Mutual labels:  social-login
heroku-nextjs-custom-server-express
Deploy Next.js server-side React apps using a custom Express server to Heroku
Stars: ✭ 91 (+40%)
Mutual labels:  heroku
craft-heroku
🍄 Craft 3, ready for continuous deployment to Heroku.
Stars: ✭ 16 (-75.38%)
Mutual labels:  heroku
iam
💚 Introduction Bot for slack teams:
Stars: ✭ 12 (-81.54%)
Mutual labels:  heroku
NatsukiMusic
Free and Open Source Channel/Group Voice chat music player for telegram ❤️ with button support, deezer and saavn playback support @ItzSadew
Stars: ✭ 23 (-64.62%)
Mutual labels:  heroku
Feedback-bot
In Short This is An Personalized Livegram Bot Made Using Python.. Follow Me @HeimanPictures & Star This Repo
Stars: ✭ 23 (-64.62%)
Mutual labels:  heroku
heroku-datadog-drain-golang
Funnel metrics from multiple Heroku apps into DataDog using statsd.
Stars: ✭ 34 (-47.69%)
Mutual labels:  heroku
ecars
Sample application for Lightning Web Components and Salesforce Platform runtime and compute capabilities. Part of the sample gallery. Electric car manufacturer use case. Get inspired and learn best practices.
Stars: ✭ 132 (+103.08%)
Mutual labels:  heroku
heroku-cli-deploy
No description or website provided.
Stars: ✭ 23 (-64.62%)
Mutual labels:  heroku
link-preview-api
Backed to provide information for link-prevue vue component
Stars: ✭ 31 (-52.31%)
Mutual labels:  heroku
newsemble
API for fetching data from news websites.
Stars: ✭ 42 (-35.38%)
Mutual labels:  heroku
PglRobot
No description or website provided.
Stars: ✭ 12 (-81.54%)
Mutual labels:  heroku
img ai app boilerplate
An image classification app boilerplate to serve your deep learning models asap!
Stars: ✭ 27 (-58.46%)
Mutual labels:  heroku
demo-laravel-crud
My practice for basic CRUD of Laravel5 on Heroku.
Stars: ✭ 22 (-66.15%)
Mutual labels:  heroku
heroku-postico
Heroku Postgres connection tool for Postico
Stars: ✭ 37 (-43.08%)
Mutual labels:  heroku
Meteor-Files-Demos
Demos for ostrio:files package
Stars: ✭ 51 (-21.54%)
Mutual labels:  heroku

Django_Social_Login_Tutorial

大家一定常看到可以使用社交平台登入的網站,

像是使用 FACEBOOKGITHUBGOOGLETWITTER 登入並註冊網站。

今天要教大家使用 Django 實現一個可以使用社交平台登入並且註冊的網站,

建議對不熟悉 Django 的朋友,可以先觀看我之前寫的 Django 基本教學 - 從無到有 Django-Beginners-Guide

如果你想看 Flask 的範例,可以參考我之前寫的 Flask-Login-example

特色

  • 基本登入以及註冊,使用社交平台登入。

  • 忘記密碼使用信箱重新設定密碼。

安裝套件

確定電腦有安裝 Python 之後

請在 cmd ( 命令提示字元 ) 輸入以下指令

pip install -r requirements.txt

我可以從這篇範例學到什麼

教學

了解 django template tag ( 自定義模板 )

我們先進去 account 資料夾裡,新增一個 templatetags 資料夾,並且在裡面建立一個空的 __init__.py

然後我們再建立一個 account_tags.py,account 資料夾裡面的結構應該像下圖

我們在 account_tags.py 裡填入以下程式碼

from django import template
from django.contrib.auth.models import User

register = template.Library()


@register.simple_tag
def total_people():
    return User.objects.count()

接著我們在 dashboard.html 裡填入下方程式碼 ( 完整程式碼請參考 dashboard.html )

{% extends "base.html" %}
{% load account_tags %}
{% block title %}Dashboard{% endblock %}
{% block content %}
    <div class="jumbotron">
        <h1>Dashboard</h1>
        <p>Welcome to your dashboard.</p>
        So far <b>{% total_people %}</b> people have tried Django Social Login Tutorial.
    </div>


    {% social_people %}



{% endblock %}

重要的是 {% load account_tags %} 以及 {% total_people %}

注意,當你加入新的 template tags ,請重新啟動你的 Django Server

使用自定義 template tags 的好處是你可以在任何的 template 中處理資料,而不用每次都要使用 views 去 render 你的資料。

Django 提供三種方法來讓你建立自己的 template tags

更多可參考官網說明 django template tag ( 自定義模板 ) 。

使用 Django 發送信件

設定 Django 在 console 中輸出 e-mail 內容來代替使用SMTP寄送郵件(測試用)。

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

如果你想要真的寄出一封郵件,請修改 settings.py

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'your_password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True

你也可以直接在 python console 中測試郵件是否會寄出

from django.core.mail import send_mail

接著寄出郵件

send_mail('Django mail', 'This e-mail was sent with Django.','[email protected]', ['[email protected]'], fail_silently=False)

本篇使用 Gmail 當作範例,其他的信箱應該大同小異,請自行研究。

一些安全性的設定,請參考我之前寫的

使用-gmail-寄信---前置作業

這裡提醒大家如果 GMAIL 一直寄信失敗,或是佈署後信件寄不出去解決方法

有兩個地方很重要,要設定,不然信件會一直無法順利寄出

允許安全性較低的應用程式 設定處於啟用狀態 要打開 !! https://myaccount.google.com/lesssecureapps

http://i.imgur.com/NbeBQjL.png

再來還有一個很重要 !!! 我有被雷到 !! 進到下方網址

https://accounts.google.com/b/0/DisplayUnlockCaptcha

授權存取您的 Google 帳戶,直接按繼續,如下圖

http://i.imgur.com/5ZIfPup.png

django-bootstrap3 使用方法,以及為什麼我們要去使用它

我們版型套用 bootstrap 來完成,

Django 在 render form 的時候,他有預設的 html 格式,不過有時候我們常常需要加入一些自己的 class。

我們有一個 form 如下

from django import forms

class UserRegistrationForm(forms.ModelForm):
    password = forms.CharField(label='Password',
                                widget=forms.PasswordInput)

Django render 出如下 html

 <input type="password" name="password" required="" id="id_password">

假如我們要加上自己的 class

依照官網的說明 customizing-widget-instances,我們可以使用下面這種方法

from django import forms

class UserRegistrationForm(forms.ModelForm):
    password = forms.CharField(label='Password',
                                widget=forms.PasswordInput(attrs={'class': 'add_class'}))

然後 render 出來的內容會變成

 <input type="password" name="password" class="add_class" required="" id="id_password">

雖然結果是我們想要的,但你會發現有點奇怪 , 因為這些東西其實應該寫在 html 裡面才對,而不是寫在 python 裡面,

這樣會不好管理 css,所以為了解決這個問題,就有 django-widget-tweaks 以及 django-bootstrap3 出現來解決這個問題,

在這邊我們使用 django-bootstrap3 ,因為我們是套用 bootstrap

django-bootstrap3 使用方法如下

{% load bootstrap3 %}

{# Display a form #}

<form action="/url/to/submit/" method="post" class="form">
    {% csrf_token %}
    {% bootstrap_form form %}
    {% buttons %}
        <button type="submit" class="btn btn-primary">
            {% bootstrap_icon "star" %} Submit
        </button>
    {% endbuttons %}
</form>

更多說明可參考 django-bootstrap3

social-auth-app-django 的使用方法 ( 社交平台登入 )

請在你的命令提示字元 (cmd ) 底下輸入

pip install social-auth-app-django

settings.py

INSTALLED_APPS = [
    ......
    'social_django',
    ......
]

接著在你的命令提示字元 (cmd ) 底下輸入

python manage.py migrate

settings.py

AUTHENTICATION_BACKENDS = (
    ......
    'social_core.backends.facebook.FacebookOAuth2',
    'social_core.backends.github.GithubOAuth2',
    'social_core.backends.google.GoogleOAuth2',
    'social_core.backends.twitter.TwitterOAuth',
    ......
)

設定 URLs

可參考本範例的 urls.py

    urlpatterns = [
    ......
    url(r'social-auth/', include('social_django.urls', namespace='social'))
]

設定 NAMESPACE

SOCIAL_AUTH_URL_NAMESPACE = 'social'

FACEBOOK

請到 https://developers.facebook.com/apps/?action=create 建立 app,

詳細教學可參考我之前寫的 facebook登入-前置作業

比較要注意的地方是請將網址設定為 http://localhost:8000/ , 並且將 fb 的應用程式網域設定為 localhost,

這樣你就可以在本地端測試,

最後請將你的 FACEBOOK KEY 以及 SECRET 貼到 settings.py

SOCIAL_AUTH_FACEBOOK_KEY = 'XXX' # Facebook App ID
SOCIAL_AUTH_FACEBOOK_SECRET = 'XXX' # Facebook App Secret

Templates 使用方法,可參考 login.html

<a href="{% url "social:begin" "facebook" %}" facebook</a>

GITHUB

請到 https://github.com/settings/applications/new 建立 app ,

本機測試設定如下

Authorization callback URL 請填入 http://localhost:8000/social-auth/complete/github/

http://i.imgur.com/qdc963N.png

最後請將你的 GITHUB KEY 以及 SECRET 貼到 settings.py

http://i.imgur.com/vVZE3Nj.png

SOCIAL_AUTH_GITHUB_KEY = 'XXX' # GITHUB App ID
SOCIAL_AUTH_GITHUB_SECRET = 'XXX' # GITHUB App Secret

Templates 使用方法,可參考 login.html

<a href="{% url "social:begin" "github" %}" github</a>

GOOGLE

請到 https://console.developers.google.com/project 建立 app

http://i.imgur.com/160MZ9Y.png

授權導向 URI 請填入http://localhost:8000/social-auth/complete/google-oauth2/

http://i.imgur.com/ygpWl2C.png

http://i.imgur.com/zsq35jn.png

最後請將你的 GOOGLE KEY 以及 SECRET 貼到 settings.py

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '' # Google Consumer Key
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '' # Google Consumer Secret

記得啟用 GOOGLE+ API

http://i.imgur.com/jR0l3Xw.png

Templates 使用方法,可參考 login.html

<a href="{% url "social:begin" "google-oauth2" %}" google</a>

TWITTER

請到 https://apps.twitter.com/app/new 建立 app ,

Callback URL 請填入 http://localhost:8000/social-auth/complete/twitter/

最後請將你的 TWITTER KEY 以及 SECRET 貼到 settings.py

SOCIAL_AUTH_TWITTER_KEY  = 'XXX' # TWITTER App ID
SOCIAL_AUTH_TWITTER_SECRET = 'XXX' # TWITTER App Secret

Templates 使用方法,可參考 login.html

<a href="{% url "social:begin" "twitter" %}" twitter</a>

執行畫面

首頁

佈署

佈署到 Heroku , 詳細教學可參考我之前寫的 Deploying_Django_To_Heroku_Tutorial

TODO

  • 佈署到 Heroku 社交平常登入 ( FACEBOOK ) 異常,但本機測試 ( localhost ) 正常。

執行環境

  • Python 3.6.0

Reference

Donation

文章都是我自己研究內化後原創,如果有幫助到您,也想鼓勵我的話,歡迎請我喝一杯咖啡😆

alt tag

贊助者付款

License

MIT license

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].