如果在Django信号中true为true,为什么还要执行block?

时间:2019-04-22 08:35:41

标签: python django if-statement django-models django-signals

我正在编写一个信号功能,该功能将在他/他注册时向用户发送注册通知电子邮件,并在他/她更新用户个人资料时发送更新通知电子邮件。为此,我使用了if-else块来检查created参数。如果为true,则用户将收到注册通知。否则,用户将收到配置文件更新通知。当更新用户对象时,它工作正常。但是,当新用户注册时,两个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='info@silatechnologies.com', 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='info@silatechnologies.com',
                  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})

1 个答案:

答案 0 :(得分:1)

假设您正在使用Django的内置注册流程,这将意味着对User模型执行2个操作:

  1. 它将创建User对象,从而通过post_save触发created=True信号,您将发送第一封电子邮件。
  2. 注册后,Django将登录用户和updates it's last_login字段,从而使用post_save触发另一个created=False信号