django - 使用 google django 创建社交身份验证功能
问题描述
您好,我是新手,有任务要做,我尝试了简单的社交身份验证,但下面有点复杂:
Create a social authentication functionality with google and add user in a
database. After adding user in a database, customer should also be created
using django signals.
Note:- Customer is one to one related with user?
我的模型.py:
class Buddy(models.Model):
user_name=models.CharField(max_length=200,blank=True,null=True)
def __str__(self):
return str(self.user_name)
class Customer(models.Model):
customer_name=models.OneToOneField(Buddy,
on_delete = models.CASCADE,
blank=True,null=True)
def __str__(self):
return str(self.customer_name)
我的settings.py包括以下几行:
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = '2377[...].apps.googleusercontent.com'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '[...]'
SOCIAL_AUTH_GOOGLE_OAUTH2_SCOPE = ['email']
INSTALLED_APPS = [ ... # oauth
'oauth2_provider',
'social_django',
'rest_framework_social_oauth2' ]
AUTHENTICATION_BACKENDS = ( # Google OAuth2
'social_core.backends.google.GoogleOAuth2',
# django-rest-framework-social-oauth2
'rest_framework_social_oauth2.backends.DjangoOAuth2', # Django
'django.contrib.auth.backends.ModelBackend', )
解决方案
您必须使用 Django 的post_save信号。
在你的models.py中有:
class Buddy(models.Model):
user_name=models.CharField(max_length=200, blank=True, null=True)
def __str__(self):
return str(self.user_name)
class Customer(models.Model):
# This translates into buddy_id when you migrate
buddy=models.OneToOneField(Buddy,on_delete = models.CASCADE,
blank=True, null=True)
customer_name = models.CharField(max_length=200, blank=True, null=True)
def __str__(self):
return str(self.customer_name)
在你的views.py中确保你有
from django.shortcuts import render
from django.db.models.signals import post_save
from .models import Buddy
from .callbacks import save_customer
# You'll customize this view to read any parameters and provide user_name
def custom_view(request):
Buddy.objects.create(user_name="SomeUsername")
# Any of your other logic comes here, specify in the dict
return render(request, 'yourpage.html', {})
# This should be at the bottom of your views.py:
post_save.connect(save_customer, sender=Buddy)
然后在同一位置创建一个名为callbacks.py的新文件,其中包括:
from .models import Buddy
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=Buddy)
def save_customer(sender, instance, **kwargs):
# Customize your OneOnOne model on a meaningful way so it will be useful
customer = Customer.objects.create(customer_name=instance.user_name)
instance.customer = customer
instance.customer.save()
在此处阅读有关 Django 信号的更多信息。
推荐阅读
- java - LastModifiedFileListFilter 用于 Sftp 入站适配器
- mysql - 3个表连接一对多
- c++ - Clang C++ new 运算符大型动态数组编译时间慢
- python - CV2 图像记忆
- java - 组合多个相同结构的sqlite数据库
- python - Python中字符串中字符组的递归消除
- javascript - 功能完成后动态导入是否被销毁?
- c# - 无法将整数从类转换为 .ToString 字符串
- python - response.url 如何知道我们请求的是哪个 url?(Scrapy)
- java - 使用响应式 mongoDB 在 Micronaut 中创建 TextIndex