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

拈花ヽ惹草 提交于 2020-01-11 09:46:10

问题


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.', 'from@example.com',
    ['to@example.com'], 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.', 'from@example.com',['to@example.com'], 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?


回答1:


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




回答2:


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.




回答3:


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...



来源:https://stackoverflow.com/questions/6593348/how-can-i-send-an-email-to-user-on-new-user-addition-to-django-admin-site

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