如何以编程方式触发Django 1.7.6中的密码重置电子邮件? [英] How to programmatically trigger password reset email in django 1.7.6?

查看:91
本文介绍了如何以编程方式触发Django 1.7.6中的密码重置电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,我必须将200多个新用户加载到django应用中,然后立即向他们发送密码重置电子邮件.这只能发生一次,仅由我执行,并在后端安静地运行.上网冲浪只能为我带来一个或多或少的正确答案:触发密码在没有浏览器的情况下在django中重置电子邮件?.唯一的问题是,这篇文章大约有4年的历史了,当然,当我尝试该解决方案时,它是行不通的...

I've encountered a problem where I had to load more than 200 new users into my django app and right away send them a password reset email. This had to happen only once, done only by me and run quietly on backend. Surfing the internet brought me only to one more or less right answer: Trigger password reset email in django without browser?. The only problem was is that this post was about 4 years old and of course when I tried the solution, it didn't work...

推荐答案

我提到的链接中两个最有价值的要点:
1)在最新版本的Django中,我们需要调用form.is_valid()
2)发送电子邮件是通过save()完成的.

Two most valuable points from the link I mentioned:
1) In more recent version of Django we need to call form.is_valid()
2) Sending of email is done upon save().

这是我查询所需用户并向他们发送密码重置链接的方式:

Here is how I queried users that I needed and sent each of them a password reset link:

    def find_users_and_send_email():
       from django.http import HttpRequest
       from django.contrib.auth.forms import PasswordResetForm
       from django.contrib.auth.models import User

       users = User.objects.filter(date_joined__gt = '2015-04-16')
       for user in users:
       try:

        if user.email:
            log.info("Sending email for to this email:", user.email)
            form = PasswordResetForm({'email': user.email})

            assert form.is_valid()
            request = HttpRequest()
            request.META['SERVER_NAME'] = 'help.mydomain.com'
            request.META['SERVER_PORT'] = '443'
            form.save(
                request= request,
                use_https=True,
                from_email="username@gmail.com", 
                    email_template_name='registration/password_reset_email.html')

       except Exception as e:
          log.info(e)
          continue

return 'done'

1)通常,PasswordResetForm与前端的请求"一起使用,而我没有.所以我只创建了一个.
2)当我按照链接中的示例进行操作时,它失败了.在请求中找不到服务器名称. (之所以有意义,是因为我无所事事地实例化了我的请求)
3)当我确定服务器名称时,它询问服务器端口.由于我使用https,因此我的端口是443,否则请使用默认端口. 4)如果您使用https,请不要忘记在保存表单( use_https = True )

1) Usually PasswordResetForm works with a "request" from the front-end, which I didn't have. So I simply created one.
2) When I followed the example in the link, it failed.. It couldn't find server name in the request. (Makes sense because I instantiated my request out of nowhere)
3) When I fixed server name, it asked for the server port. Since I used https, my port is 443, otherwise use default port. 4) If you use https, don't forget to indicate it when you save the form (use_https=True)

这篇关于如何以编程方式触发Django 1.7.6中的密码重置电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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