Skip to main content
 首页 » 编程设计

python之在使用 djanago-allauth 发出 post_save 信号后,如何发送电子邮件确认邮件

2024年10月25日31xing901022

我在我的网络应用程序中使用 django-allauth 进行帐户管理。

我有用户模型和用户配置文件模型。

当用户注册时,它会创建一个用户(用户模型中的一个实例)。

UserProfile 与模型 User 相关联。

Allauth默认在用户注册时发送一封邮件,用户注册时会发送一封确认邮件。

现在我只想在他填写 UserProfile 时发送该电子邮件。

我想在这里使用信号。 当用户填写 UserProfile 时,它​​将调用 post_save 信号,它调用另一个函数 user_signed_up_ 但我在将请求和用户参数传递给该函数时遇到问题。

这是我的模型.py

from django.db import models 
from django.contrib.auth.models import User 
from allauth.account.signals import user_signed_up 
from allauth.account.utils import send_email_confirmation 
from django.dispatch import receiver 
import datetime 
 
class UserProfile(models.Model): 
    user = models.ForeignKey(User, unique=True) 
 
    are_u_intrested = models.BooleanField(default=False) 
 
 
#this signal will be called when user signs up.allauth will send this signal. 
 
@receiver(user_signed_up, dispatch_uid="some.unique.string.id.for.allauth.user_signed_up") 
def user_signed_up_(request, user, **kwargs): 
 
    send_email_confirmation(request, user, signup=True) 
    #this allauth util method, which sends confirmation email to user. 
 
 
 
 
 
models.signals.post_save.connect(user_signed_up_, sender=UserProfile, dispatch_uid="update_stock_count") 
 
#If user fills this userProfile , then I only send confirmation mail. 
#If UserProfile model instace saved , then it send post_save signal. 

请您参考如下方法:

你不需要在这里使用allauth的信号,你需要使用Django的模型信号。像这样的东西:

from django.db.models.signals import post_save 
from django.dispatch import receiver 
 
@receiver(post_save, sender=UserProfile) 
def userprofile_filled_out(sender, instance, created, raw, **kwargs): 
    # Don't want to send it on creation or raw most likely  
    if created or raw: 
        return 
 
    # Test for existence of fields we want to be populated before 
    # sending the email 
    if instance.field_we_want_populated: 
       send_mail(...) 

希望对您有所帮助!