Anshul
Anshul

Reputation: 7964

How can I send an email to user on new user addition to django admin site?

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

Answers (3)

lprsd
lprsd

Reputation: 87095

There are multiple problems I can see in the code as I can see it, above.

  • First, the 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

Mp0int
Mp0int

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 need django 1.3, so check your django version with python manage.py version and update it if required...
  • Best place for your your models.py files

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

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798676

You want to hook the post_save signal for the User model.

Upvotes: 1

Related Questions