创建用户对象时是否有方式发送用户电子邮件? [英] Is there a way to send a user email when user object is created?

查看:111
本文介绍了创建用户对象时是否有方式发送用户电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在系统中我正在建立用户不能自己注册。用户由系统管理员之一添加。所以没有用户注册表或视图。注册只在管理员中进行,所以我猜想send_mail也要在那里(或我错了)?



我需要发送一个自动电子邮件当用户创建时,只有这样(不是每个模型的保存)。



可以帮助吗?那里有内置的东西吗?或者我该怎么做?



我已经阅读了关于create_user用户管理器的信息,但是我认为编辑管理员的方法更好。 b $ b

解决方案

您可以在 post_save 信号为用户模型。在某个地方:

 #注意:未经测试的代码

from django.db.models。信号导入post_save
from django.contrib.auth.models import User

def email_new_user(sender,** kwargs):
如果kwargs [created]:#仅适用于新用户
new_user = kwargs。[instance]
#发送电子邮件到new_user.email ..

post_save.connect(email_new_user,sender = User)

注意如果kwargs [created]:检查这是否是新创建的用户实例。


In the system I am building user CAN NOT register them selves. The users are added by one of the system admins. So there is no user registration form or view. The registration is only being done in the admin so I guess that the send_mail has to be over there also (or am I wrong)?

I need to send an automatic email to the user when he/she is being created and only then (not on every save of the model).

Can any one help with this? Is there a built-in something for that? or how do I do that?

I've read about the create_user user Manager, but I thought there is a better way then editing a manager.

解决方案

You can register a callback on the post_save signal for the User model. Somewhere along the lines of:

# note: untested code

from django.db.models.signals import post_save
from django.contrib.auth.models import User

def email_new_user(sender, **kwargs):
    if kwargs["created"]:  # only for new users
        new_user = kwargs.["instance"]
        # send email to new_user.email ..

post_save.connect(email_new_user, sender=User)

Note the if kwargs["created"]: condition which checks if this is a newly created User instance.

这篇关于创建用户对象时是否有方式发送用户电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆