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...
Two most valuable points from the link I mentioned:
form.is_valid()
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
import logging
logger = logging.getLogger(__name__)
users = User.objects.filter(date_joined__gt = '2015-04-16')
for user in users:
try:
if user.email:
logger.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:
logger.warning(str(e))
continue
return 'done'
PasswordResetForm
works with a "request" from the front-end, which I didn't have. So I simply created one.use_https=True