我正在编写一个信号功能,当他/她注册时会向用户发送注册通知电子邮件,并在他/她更新用户配置文件时发送更新通知电子邮件。为此,我使用了if-else块来检查created
参数。如果是,则用户将收到注册通知。否则,用户将收到配置文件更新通知。更新用户对象时,它工作正常。但是当新用户注册时,if和else块都在执行,新注册用户会收到两个电子邮件通知:一个注册通知和一个配置文件更新通知。完整的信号代码如下:
#myapp/signals.py
from django.core.mail import send_mail
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.template.loader import render_to_string
from django.utils.html import strip_tags
#getting custom user model
User = get_user_model()
@receiver(post_save, sender=User)
def send_user_notification(sender, instance, created, **kwargs):
if created:
subject = 'Signup Notification'
html_message = render_to_string(
'email/signup_notification.html',
{
'username': instance.username,
'email': instance.email,
}
)
message = strip_tags(html_message)
send_mail(subject, message, from_email='[email protected]', recipient_list=[instance.email,],
html_message=html_message)
else:
send_mail(subject='Your profile on Sila Crowdfunding updated!',
message='Dear ' + instance.username + ', your profile information is updated successfully.',
from_email='[email protected]',
recipient_list=[instance.email, ]
)
我也使用if not created
而不是else
。但我得到了同样的结果。任何人都可以提供任何解决方案吗?提前致谢。
我的注册用户视图功能可能有助于解决问题。这是视图功能:
def signup(request):
"""
Render signup form if request is GET else create user
"""
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'registration/signup.html', {'form': form})
假设您正在使用Django的内置注册流程,这将意味着对User
模型的两个操作:
User
对象,从而用post_save
发射created=True
信号,你将发送第一封电子邮件。last_login
字段,从而用post_save
发射另一个created=False
信号