Is there a way to send a user email when user object is created?

佐手、 提交于 2019-12-10 22:17:27

问题


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.


回答1:


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.




回答2:


You can use the signals framework. A post-save signal on User objects will be appropriate, see here for a similar example.




回答3:


Use the post_save signal, which has a created argument sent with the signal. If created is true, send your email.

Edit

Shawn Chin beat me to it. Accept his answer



来源:https://stackoverflow.com/questions/6583212/is-there-a-way-to-send-a-user-email-when-user-object-is-created

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!