Reputation: 7964
I want to send an email with login details to user emailaddress whenever Admin adds new user to admin site.
I know Django provides send_mail module for that,but I don't know where should I put this code and override some view to send automatic mails on new user addition.
from django.core.mail import send_mail
send_mail('Subject here', 'Here is the message.', '[email protected]',
['[email protected]'], fail_silently=False)
How can i do it?
I tried putting this code in my models.py
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"]
print new_user.email
#send_mail('Subject here', 'Here is the message.', '[email protected]',['[email protected]'], fail_silently=False)
post_save.connect(email_new_user, sender=User)
But its not printing anything on command line. I think the function is not getting called whenever i create a new user.Don't know why?
Upvotes: 3
Views: 5004
Reputation: 87095
There are multiple problems I can see in the code as I can see it, above.
def email_new_user()
is wrongly indented. If that is not a formatting error here, correct it.new_user = kwargs.["instance"]
is wrong syntax. It really should be kwargs["instance"]
And then, do you have an SMTP server running? Can you send email from the shell? If not, configure that and then try it again. It should work.
Upvotes: 3
Reputation: 18727
One possible problem was, Django user cretion consists of two steps. First django asks for username, password and password confirmation, and when you press save (or save and continue edit) your save method fired without e-mail information. Since django will accept that request as a newly created record, your signal will fire for a record with no e-mail information...
If django handles admin save diffrently and do not mark a newly created record instance as created you shall not have any problem, but probably django will not do that.
UPDATE: Some possible reasons are:
You can put signal handling and registration code anywhere you like. However, you'll need to make sure that the module it's in gets imported early on so that the signal handling gets registered before any signals need to be sent. This makes your app's models.py a good place to put registration of signal handlers.
These are basic problems...
Upvotes: 0
Reputation: 798676
You want to hook the post_save
signal for the User
model.
Upvotes: 1