[英]In Django's auth contrib module, how do I invoke the function that generates a password reset email?
I'm using Django 3.1.1 with the auth contrib module.我将 Django 3.1.1 与 auth contrib 模块一起使用。 I would like to send the user an email when they request their password be reset (via an API call) so I created this in my urls.py file
当用户请求重置密码时(通过 API 调用),我想向用户发送一个 email,所以我在我的 urls.py 文件中创建了这个
path('reset_password', views.ResetPasswordView.as_view(template_name='../templates/users/password_reset.html'), name='reset_password'),
and added this to my views.py file并将其添加到我的 views.py 文件中
class ResetPasswordView(SuccessMessageMixin, PasswordResetView):
reset_password_template_name = 'templates/users/password_reset.html'
email_template_name = 'users/password_reset_email.html'
subject_template_name = 'users/password_reset_subject'
success_message = "We've emailed you instructions for setting your password, " \
"if an account exists with the email you entered. You should receive them shortly." \
" If you don't receive an email, " \
"please make sure you've entered the address you registered with, and check your spam folder."
success_url = reverse_lazy('users-home')
@method_decorator(csrf_exempt)
def dispatch(self, request, *args, **kwargs):
request.csrf_processing_done = True
return super().dispatch(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
email = json.loads(request.body).get('username')
try:
if User.objects.get(email=email).is_active:
print("email: %s " % email)
return super(ResetPasswordView, self).post(request, *args, **kwargs)
except:
# this for if the email is not in the db of the system
return super(ResetPasswordView, self).post(request, *args, **kwargs)
but when I call my reset password endpoint with a user that exists, I simply get the contents of my template returned from the endpoint.但是当我用一个存在的用户调用我的重置密码端点时,我只是从端点返回我的模板的内容。 How do I configure things such that the contents of the template are emailed to the user?
如何配置以将模板内容通过电子邮件发送给用户? That is, I want the user to receive the reset password email with a valid link to reset their password.
也就是说,我希望用户收到重置密码 email 以及用于重置密码的有效链接。
Generating a reset url and sending the email is done upon save()
of django.contrib.auth.forms.PasswordResetForm .生成重置 url 并发送 email 是在django.contrib.auth.forms.PasswordResetForm的
save()
上完成的。
Here is an example:这是一个例子:
from django.contrib.auth.forms import PasswordResetForm
from django.http import HttpRequest
form = PasswordResetForm({'email': user.email})
if form.is_valid():
request = HttpRequest()
request.META['SERVER_NAME'] = 'example.com'
request.META['SERVER_PORT'] = '443'
# calling save() sends the email
# check the form in the source code for the signature and defaults
form.save(request=request,
use_https=True,
from_email="noreply@example.com",
email_template_name='registration/password_reset_email.html')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.