django-allauth实现第三方登录的示例代码
时间: 2023-01-11 16:55:36 浏览: 77
好的,这是一个简单的 django-allauth 实现第三方登录的示例:
1. 在 Django 项目中安装 django-allauth 库:
```
pip install django-allauth
```
2. 在 Django 的 settings.py 文件中添加 allauth 应用,并设置所需的认证提供程序(例如 Google,Facebook 等):
```python
INSTALLED_APPS = (
...
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.google',
'allauth.socialaccount.providers.facebook',
...
)
SOCIALACCOUNT_PROVIDERS = {
'google': {
'SCOPE': [
'profile',
'email',
],
'AUTH_PARAMS': {
'access_type': 'online',
}
},
'facebook': {
'METHOD': 'oauth2',
'SCOPE': ['email', 'public_profile'],
'AUTH_PARAMS': {'auth_type': 'reauthenticate'},
'FIELDS': [
'id',
'email',
'name',
'first_name',
'last_name',
'verified',
'locale',
'timezone',
'link',
'gender',
'updated_time',
],
'EXCHANGE_TOKEN': True,
'LOCALE_FUNC': lambda request: 'en_US',
'VERIFIED_EMAIL': False,
'VERSION': 'v2.12',
}
}
```
3. 在 Django 的 urls.py 文件中添加 allauth 的 URL 路径:
```python
urlpatterns = [
...
path('accounts/', include('allauth.urls')),
...
]
```
4. 在 Django 的 templates 目录中创建一个 base.html 文件,并在该文件中添加登录/注册的链接:
```html
<div>
{% if user.is_authenticated %}
<a href="{% url 'account_logout' %}">Logout</a>
{% else %}
<a href="{% url 'account_login' %}">Login</a>
<a href="{% url 'account_signup' %}">Signup</a>
{% endif %}
</div>
```