使用post_save在数据库条目创建时发送电子邮件

时间:2016-05-25 11:33:41

标签: python django django-views

我需要在创建新用户时使用django中的post_save函数发送电子邮件。身份验证和创建在后端本身的views.py中完成, 我如何整合到代码中如下 -

def signup(request):
if request.method == 'POST':
    try:
        username = request.POST.get('username')
        firstname = request.POST.get('first_name')
        password = request.POST.get('password')
        lastname = request.POST.get('last_name', '')
        email = request.POST.get('email')
        contact_num = request.POST.get('mobile_number', '')
        try:
            user = Customer(username=username, first_name=firstname,
                            last_name=lastname, email=email, mobile_number=contact_num,
                            is_staff=False, is_superuser=False,
                            is_active=True, last_login=now.date(), )
            user.set_password(password)
            user.save()
            user = auth.authenticate(username=username, password=password)

            try:
                context = {"customer_name": firstname}
                html = render_to_string('email_templates/welcome.html', context)
                tasks.send_welcome_email(email, html)
            except Exception as e:
                logger.error("Error while sending Welcome email on signup {}".format(e.message))
        except Exception as e:
            logger.error("Constraint violation new user Signup", e.message)
            c = {}
            c.update(csrf(request))
            return render(request, 'login.html',
                          {'user': False, 'c': c, 'Error': 'Username or Email exist already,Try again'})
        if user is not None and user.is_active:
            auth.login(request, user)
            if request.user.is_authenticated():
                return HttpResponseRedirect('/')
            else:
                return HttpResponseRedirect('/accounts/login/')
        else:
            return HttpResponseRedirect('/404/')
    except Exception as e:
        logger.error("Exception in new user Signup", e.message)
        return HttpResponseRedirect('/500/')
else:
    if check_authentication(request):
        return HttpResponseRedirect('/404/')
    else:
        try:
            c = {}
            c.update(csrf(request))
            return render(request, 'login.html', {'user': False, 'c': c})
        except Exception as e:
            logger.error("Exception in generating csrf for login form", e.message)
            return HttpResponseRedirect('/500/')

以上是用户创建的代码。任何关于使代码更好的建议也是受欢迎的。

1 个答案:

答案 0 :(得分:1)

IMO,您可以使用signals发送电子邮件,而不是直接在视图中发送电子邮件。 This post展示了如何很好地使用这些信号。

此外,您可以使用created的键kwargs来检查实例是否已创建。

@receiver(post_save, sender=User)
def user_post_save(sender, **kwargs):
    if kwargs['created']: # true if the instance is created
        # send email for the new user...