在Django的auth contrib模块中,如何调用生成密码重置邮件的函数?

f0brbegy  于 2023-01-03  发布在  Go
关注(0)|答案(1)|浏览(120)

我使用Django 3.1.1的auth contrib模块,我想在用户请求重置密码时给他们发一封邮件(通过API调用),所以我在www.example.com文件中创建了这个urls.py

path('reset_password', views.ResetPasswordView.as_view(template_name='../templates/users/password_reset.html'), name='reset_password'),

并将其添加到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)

但是,当我调用已存在的用户的重置密码端点时,我只会从端点返回模板的内容。如何进行配置,以便将模板的内容通过电子邮件发送给用户?也就是说,我希望用户收到包含重置密码的有效链接的重置密码电子邮件。

l3zydbqr

l3zydbqr1#

生成重置URL和发送电子邮件是在django.contrib.auth.forms.PasswordResetForm的save()上完成的。
下面是一个例子:

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')

相关问题