{"id":20619748,"url":"https://github.com/twtrubiks/django_social_login_tutorial","last_synced_at":"2025-04-15T12:12:20.842Z","repository":{"id":84518936,"uuid":"96667359","full_name":"twtrubiks/django_social_login_tutorial","owner":"twtrubiks","description":"Django Social Login Tutorial","archived":false,"fork":false,"pushed_at":"2022-06-29T01:58:57.000Z","size":25,"stargazers_count":65,"open_issues_count":0,"forks_count":23,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-04-15T12:12:01.692Z","etag":null,"topics":["django","heroku","send-email","social-login","tutorial"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/twtrubiks.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-07-09T07:06:34.000Z","updated_at":"2024-10-15T06:27:37.000Z","dependencies_parsed_at":"2023-03-02T04:30:27.910Z","dependency_job_id":null,"html_url":"https://github.com/twtrubiks/django_social_login_tutorial","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fdjango_social_login_tutorial","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fdjango_social_login_tutorial/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fdjango_social_login_tutorial/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/twtrubiks%2Fdjango_social_login_tutorial/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/twtrubiks","download_url":"https://codeload.github.com/twtrubiks/django_social_login_tutorial/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249067779,"owners_count":21207396,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["django","heroku","send-email","social-login","tutorial"],"created_at":"2024-11-16T12:12:25.050Z","updated_at":"2025-04-15T12:12:20.833Z","avatar_url":"https://github.com/twtrubiks.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Django_Social_Login_Tutorial\n\n* [線上 Demo 網站](https://django-social-login-tutorial.herokuapp.com/account/login/?next=/account/)\n\n* [Youtube 教學](https://youtu.be/Rw1lZq_lOSA)\n\n大家一定常看到可以使用社交平台登入的網站，\n\n像是使用 [FACEBOOK](https://www.facebook.com/) ， [GITHUB](https://github.com/)，\n[GOOGLE](https://plus.google.com/collections/featured?hl=zh_tw)\n，\n[TWITTER](https://twitter.com/?lang=zh-tw) 登入並註冊網站。\n\n今天要教大家使用  [Django](https://www.djangoproject.com/) 實現一個可以使用社交平台登入並且註冊的網站，\n\n建議對不熟悉 [Django](https://www.djangoproject.com/) 的朋友，可以先觀看我之前寫的 [Django 基本教學 - 從無到有 Django-Beginners-Guide](https://github.com/twtrubiks/django-tutorial)，\n\n如果你想看 [Flask](http://flask.pocoo.org/)  的範例，可以參考我之前寫的 [Flask-Login-example](https://github.com/twtrubiks/Flask-Login-example)。\n\n## 特色\n\n* 基本登入以及註冊，使用社交平台登入。\n\n* 忘記密碼使用信箱重新設定密碼。\n\n## 安裝套件\n\n確定電腦有安裝 [Python](https://www.python.org/) 之後\n\n請在  cmd  ( 命令提示字元 ) 輸入以下指令\n\n```cmd\npip install -r requirements.txt\n```\n\n## 我可以從這篇範例學到什麼\n\n* 對 [Django](https://www.djangoproject.com/) 有更深入的認識並且了解他的強大。\n\n* 了解 [django template tag](https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/)  ( 自定義模板 ) 。\n\n* 使用 [Django](https://www.djangoproject.com/)  發送信件。\n\n* 了解 [django-bootstrap3](https://github.com/dyve/django-bootstrap3) 使用方法，以及為什麼我們要去使用它。\n\n* [Django](https://www.djangoproject.com/) 的 authentication  以及 [social-auth-app-django](https://github.com/python-social-auth/social-app-django) 的使用方法 ( 社交平台登入 )。\n\n* 少踩幾個雷 QQ。\n\n## 教學\n\n### 了解 [django template tag](https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/)  ( 自定義模板 )\n\n我們先進去 account 資料夾裡，新增一個 templatetags 資料夾，並且在裡面建立一個空的 `__init__.py`，\n\n然後我們再建立一個 `account_tags.py`，account 資料夾裡面的結構應該像下圖\n\n![](http://i.imgur.com/fQe3AYA.png)\n\n我們在 `account_tags.py` 裡填入以下程式碼\n\n```python\nfrom django import template\nfrom django.contrib.auth.models import User\n\nregister = template.Library()\n\n\n@register.simple_tag\ndef total_people():\n    return User.objects.count()\n```\n\n接著我們在 `dashboard.html` 裡填入下方程式碼 ( 完整程式碼請參考 [dashboard.html](https://github.com/twtrubiks/django_social_login_tutorial/blob/master/account/templates/account/dashboard.html) )\n\n```html\n{% extends \"base.html\" %}\n{% load account_tags %}\n{% block title %}Dashboard{% endblock %}\n{% block content %}\n    \u003cdiv class=\"jumbotron\"\u003e\n        \u003ch1\u003eDashboard\u003c/h1\u003e\n        \u003cp\u003eWelcome to your dashboard.\u003c/p\u003e\n        So far \u003cb\u003e{% total_people %}\u003c/b\u003e people have tried Django Social Login Tutorial.\n    \u003c/div\u003e\n\n\n    {% social_people %}\n\n\n\n{% endblock %}\n\n```\n\n重要的是 ***{% load account_tags %}*** 以及 ***{% total_people %}***\n\n***注意，當你加入新的 template tags ，請重新啟動你的 Django Server***\n\n使用自定義 template tags 的好處是你可以在任何的 template 中處理資料，而不用每次都要使用 views 去 render 你的資料。\n\nDjango 提供三種方法來讓你建立自己的  template tags\n\n* [Simple tags](https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/#simple-tags)\n* [Inclusion tags](https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/#inclusion-tags)\n* [Assignment tags](https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/#assignment-tags)\n\n更多可參考官網說明   [django template tag](https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/)  ( 自定義模板 ) 。\n\n### 使用 [Django](https://www.djangoproject.com/)  發送信件\n\n設定 Django 在 console 中輸出 e-mail 內容來代替使用SMTP寄送郵件（測試用）。\n\n```python\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n```\n\n如果你想要真的寄出一封郵件，請修改 [settings.py](https://github.com/twtrubiks/django_social_login_tutorial/blob/master/django_social_login_tutorial/settings.py)\n\n```python\nEMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'\n```\n\n```python\nEMAIL_HOST = 'smtp.gmail.com'\nEMAIL_HOST_USER = 'your_account@gmail.com'\nEMAIL_HOST_PASSWORD = 'your_password'\nEMAIL_PORT = 587\nEMAIL_USE_TLS = True\n```\n\n你也可以直接在 python console 中測試郵件是否會寄出\n\n\u003efrom django.core.mail import send_mail\n\n接著寄出郵件\n\n\u003esend_mail('Django mail', 'This e-mail was sent with Django.','your_account@gmail.com', ['your_account@gmail.com'], fail_silently=False)\n\n本篇使用 Gmail 當作範例，其他的信箱應該大同小異，請自行研究。\n\n一些設定，請參考我之前寫的\n\n[使用 gmail 寄信---前置作業](https://github.com/twtrubiks/Flask-Mail-example#使用-gmail-寄信---前置作業)\n\n### [django-bootstrap3](https://github.com/dyve/django-bootstrap3) 使用方法，以及為什麼我們要去使用它\n\n我們版型套用 [bootstrap](http://getbootstrap.com/) 來完成，\n\nDjango 在 render form 的時候，他有預設的 html 格式，不過有時候我們常常需要加入一些自己的 class。\n\n我們有一個 form 如下\n\n```python\nfrom django import forms\n\nclass UserRegistrationForm(forms.ModelForm):\n    password = forms.CharField(label='Password',\n                                widget=forms.PasswordInput)\n```\n\nDjango render 出如下 html\n\n```html\n \u003cinput type=\"password\" name=\"password\" required=\"\" id=\"id_password\"\u003e\n```\n\n假如我們要加上自己的 class\n\n依照官網的說明 [customizing-widget-instances](https://docs.djangoproject.com/en/dev/ref/forms/widgets/#customizing-widget-instances)，我們可以使用下面這種方法\n\n```python\nfrom django import forms\n\nclass UserRegistrationForm(forms.ModelForm):\n    password = forms.CharField(label='Password',\n                                widget=forms.PasswordInput(attrs={'class': 'add_class'}))\n```\n\n然後 render 出來的內容會變成\n\n```html\n \u003cinput type=\"password\" name=\"password\" class=\"add_class\" required=\"\" id=\"id_password\"\u003e\n```\n\n雖然結果是我們想要的，但你會發現有點奇怪 , 因為這些東西其實應該寫在 html 裡面才對，而不是寫在 python 裡面，\n\n這樣會不好管理 css，所以為了解決這個問題，就有 [django-widget-tweaks](https://github.com/kmike/django-widget-tweaks) 以及 [django-bootstrap3](https://github.com/dyve/django-bootstrap3) 出現來解決這個問題，\n\n在這邊我們使用 [django-bootstrap3](https://github.com/dyve/django-bootstrap3) ，因為我們是套用 [bootstrap](http://getbootstrap.com/) ，\n\n [django-bootstrap3](https://github.com/dyve/django-bootstrap3)  使用方法如下\n\n```html\n{% load bootstrap3 %}\n\n{# Display a form #}\n\n\u003cform action=\"/url/to/submit/\" method=\"post\" class=\"form\"\u003e\n    {% csrf_token %}\n    {% bootstrap_form form %}\n    {% buttons %}\n        \u003cbutton type=\"submit\" class=\"btn btn-primary\"\u003e\n            {% bootstrap_icon \"star\" %} Submit\n        \u003c/button\u003e\n    {% endbuttons %}\n\u003c/form\u003e\n```\n\n更多說明可參考 [django-bootstrap3](https://github.com/dyve/django-bootstrap3)\n\n### [social-auth-app-django](https://github.com/python-social-auth/social-app-django) 的使用方法  ( 社交平台登入 )\n\n請在你的命令提示字元 (cmd ) 底下輸入\n\n\u003e pip install social-auth-app-django\n\n [settings.py](https://github.com/twtrubiks/django_social_login_tutorial/blob/master/django_social_login_tutorial/settings.py)\n\n```python\nINSTALLED_APPS = [\n    ......\n    'social_django',\n    ......\n]\n```\n\n接著在你的命令提示字元 (cmd ) 底下輸入\n\u003e python manage.py migrate\n\n[settings.py](https://github.com/twtrubiks/django_social_login_tutorial/blob/master/django_social_login_tutorial/settings.py)\n\n```python\nAUTHENTICATION_BACKENDS = (\n    ......\n    'social_core.backends.facebook.FacebookOAuth2',\n    'social_core.backends.github.GithubOAuth2',\n    'social_core.backends.google.GoogleOAuth2',\n    'social_core.backends.twitter.TwitterOAuth',\n    ......\n)\n```\n\n設定 URLs\n\n可參考本範例的 [urls.py](https://github.com/twtrubiks/django_social_login_tutorial/blob/master/django_social_login_tutorial/urls.py)\n\n```python\nurlpatterns = [\n    ......\n    path('social-auth/', include('social_django.urls', namespace='social'))\n]\n```\n\n設定 NAMESPACE\n\n```python\nSOCIAL_AUTH_URL_NAMESPACE = 'social'\n```\n\n***[FACEBOOK](https://www.facebook.com/)***\n\n請到 [https://developers.facebook.com/apps/?action=create](https://developers.facebook.com/apps/?action=create) 建立 app，\n\n詳細教學可參考我之前寫的 [facebook登入-前置作業](https://github.com/twtrubiks/Flask-Login-example#使用facebook登入-前置作業)，\n\n比較要注意的地方是請將網址設定為 [http://localhost:8000/](http://localhost:8000/)  ， 並且將 fb 的應用程式網域設定為 localhost，\n\n這樣你就可以在本地端測試，\n\n最後請將你的 FACEBOOK KEY 以及  SECRET 貼到  [settings.py](https://github.com/twtrubiks/django_social_login_tutorial/blob/master/django_social_login_tutorial/settings.py)\n\n```python\nSOCIAL_AUTH_FACEBOOK_KEY = 'XXX' # Facebook App ID\nSOCIAL_AUTH_FACEBOOK_SECRET = 'XXX' # Facebook App Secret\n```\n\nTemplates 使用方法，可參考 [login.html](https://github.com/twtrubiks/django_social_login_tutorial/blob/master/account/templates/registration/login.html)\n\n```python\n\u003ca href=\"{% url \"social:begin\" \"facebook\" %}\" facebook\u003c/a\u003e\n```\n\n***[GITHUB](https://github.com/)***\n\n請到 [https://github.com/settings/applications/new](https://github.com/settings/applications/new) 建立 app ，\n\n本機測試設定如下\n\nAuthorization callback URL 請填入 [http://localhost:8000/social-auth/complete/github/](http://localhost:8000/social-auth/complete/github/)\n\n![http://i.imgur.com/qdc963N.png](http://i.imgur.com/qdc963N.png)\n\n最後請將你的 GITHUB KEY 以及  SECRET 貼到  [settings.py](https://github.com/twtrubiks/django_social_login_tutorial/blob/master/django_social_login_tutorial/settings.py)\n\n![http://i.imgur.com/vVZE3Nj.png](http://i.imgur.com/vVZE3Nj.png)\n\n```python\nSOCIAL_AUTH_GITHUB_KEY = 'XXX' # GITHUB App ID\nSOCIAL_AUTH_GITHUB_SECRET = 'XXX' # GITHUB App Secret\n```\n\nTemplates 使用方法，可參考 [login.html](https://github.com/twtrubiks/django_social_login_tutorial/blob/master/account/templates/registration/login.html)\n\n```python\n\u003ca href=\"{% url \"social:begin\" \"github\" %}\" github\u003c/a\u003e\n```\n\n[GOOGLE](https://plus.google.com/collections/featured?hl=zh_tw)\n\n請到 [https://console.developers.google.com/project](https://console.developers.google.com/project) 建立 app\n\n![http://i.imgur.com/160MZ9Y.png](http://i.imgur.com/160MZ9Y.png)\n\n授權導向 URI 請填入[http://localhost:8000/social-auth/complete/google-oauth2/](http://localhost:8000/social-auth/complete/google-oauth2/)\n\n![http://i.imgur.com/ygpWl2C.png](http://i.imgur.com/ygpWl2C.png)\n\n![http://i.imgur.com/zsq35jn.png](http://i.imgur.com/zsq35jn.png)\n\n最後請將你的 GOOGLE KEY 以及  SECRET 貼到  [settings.py](https://github.com/twtrubiks/django_social_login_tutorial/blob/master/django_social_login_tutorial/settings.py)\n\n```python\nSOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '' # Google Consumer Key\nSOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '' # Google Consumer Secret\n```\n\n記得啟用 GOOGLE+ API\n\n![http://i.imgur.com/jR0l3Xw.png](http://i.imgur.com/jR0l3Xw.png)\n\nTemplates 使用方法，可參考 [login.html](https://github.com/twtrubiks/django_social_login_tutorial/blob/master/account/templates/registration/login.html)\n\n```python\n\u003ca href=\"{% url \"social:begin\" \"google-oauth2\" %}\" google\u003c/a\u003e\n```\n\n[TWITTER](https://twitter.com/?lang=zh-tw)\n\n請到 [https://developer.twitter.com/en/portal/projects-and-apps](https://developer.twitter.com/en/portal/projects-and-apps) 建立 app,\n\n Callback URL 請填入 [http://localhost:8000/social-auth/complete/twitter/](http://localhost:8000/social-auth/complete/twitter/)\n\n![](http://i.imgur.com/V3JeGul.png)\n\n![](http://i.imgur.com/l5WgbUF.png)\n\n最後請將你的 TWITTER KEY 以及  SECRET 貼到  [settings.py](https://github.com/twtrubiks/django_social_login_tutorial/blob/master/django_social_login_tutorial/settings.py)\n\n```python\nSOCIAL_AUTH_TWITTER_KEY  = 'XXX' # TWITTER App ID\nSOCIAL_AUTH_TWITTER_SECRET = 'XXX' # TWITTER App Secret\n```\n\nTemplates 使用方法，可參考 [login.html](https://github.com/twtrubiks/django_social_login_tutorial/blob/master/account/templates/registration/login.html)\n\n```python\n\u003ca href=\"{% url \"social:begin\" \"twitter\" %}\" twitter\u003c/a\u003e\n```\n\n## 執行畫面\n\n首頁\n\n![](http://i.imgur.com/ZZYSMrY.png)\n\n![](http://i.imgur.com/5aOizNJ.png)\n\n![](http://i.imgur.com/42qUQ83.png)\n\n![](http://i.imgur.com/Ebk14a7.png)\n\n## 佈署\n\n佈署到 [Heroku](https://dashboard.heroku.com/),\n\n詳細教學可參考我之前寫的 [Deploying_Django_To_Heroku_Tutorial](https://github.com/twtrubiks/Deploying_Django_To_Heroku_Tutorial)\n\n### 建議使用 WhiteNoise 佈署\n\n```cmd\npip3 install whitenoise\n```\n\n這樣靜態檔案才會正常顯示.\n\n詳細說明可參考 [Using WhiteNoise with Django](https://whitenoise.evans.io/en/stable/django.html)\n\n在 [settings.py](https://github.com/twtrubiks/django_social_login_tutorial/blob/master/django_social_login_tutorial/settings.py) 中加入以下東西,\n\n記得把 DEBUG 修改為 `False`\n\n```python\nDEBUG = False\n```\n\n設定 STATIC_ROOT\n\n```python\nSTATIC_ROOT = BASE_DIR / \"staticfiles\"\n```\n\n設定 WhiteNoise 到 MIDDLEWARE\n\n```python\nMIDDLEWARE = [\n    # ...\n    \"django.middleware.security.SecurityMiddleware\",\n    \"whitenoise.middleware.WhiteNoiseMiddleware\",\n    # ...\n]\n```\n\nAdd compression\n\n```python\nSTATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\n```\n\n最後執行 `python3 manage.py collectstatic`\n\n如果沒有任何錯誤, 再將產生出來的東西一起 push 到 Heroku 上.\n\n## TODO\n\n- [ ] 佈署到 [Heroku](https://dashboard.heroku.com/)  社交平常登入 ( FACEBOOK ) 異常，但本機測試 ( localhost ) 正常。\n\n## 執行環境\n\n* Python 3.9\n\n## Reference\n\n* [Django](https://www.djangoproject.com/)\n* [social-auth-app-django](https://github.com/python-social-auth/social-app-django)\n* [django-bootstrap3](https://github.com/dyve/django-bootstrap3)\n* [login template](https://bootsnipp.com/snippets/o85lM)\n* [bootstrap](http://getbootstrap.com/)\n\n## Donation\n\n文章都是我自己研究內化後原創，如果有幫助到您，也想鼓勵我的話，歡迎請我喝一杯咖啡:laughing:\n\n![alt tag](https://i.imgur.com/LRct9xa.png)\n\n[贊助者付款](https://payment.opay.tw/Broadcaster/Donate/9E47FDEF85ABE383A0F5FC6A218606F8)\n\n## License\n\nMIT license\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftwtrubiks%2Fdjango_social_login_tutorial","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftwtrubiks%2Fdjango_social_login_tutorial","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftwtrubiks%2Fdjango_social_login_tutorial/lists"}