You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Django(dj_rest_auth)密码重置邮件链接至前端页面?

解决Django dj_rest_auth密码重置邮件链接指向前端的方案

1. 纠正序列化器的错误用法

你之前误将email_template_name设为前端URL,这个参数是用来指定邮件模板文件路径的,并非直接填写跳转地址。正确做法是在序列化器中生成前端重置链接,传入邮件模板上下文:

# serializers.py
from dj_rest_auth.serializers import PasswordResetSerializer
from django.conf import settings
from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_bytes

class CustomPasswordResetSerializer(PasswordResetSerializer):
    def get_email_options(self):
        # 生成与后端一致的uid和token
        user = self.get_user()
        uid = urlsafe_base64_encode(force_bytes(user.pk))
        token = self.context['view'].token_generator.make_token(user)
        
        # 拼接前端密码重置页面URL,携带uid和token参数
        frontend_reset_url = f"{settings.FRONTEND_DOMAIN}/new-password?uid={uid}&token={token}"
        
        return {
            'email_template_name': 'accounts/password_reset_email.html',  # 自定义邮件模板路径
            'extra_email_context': {
                'frontend_reset_url': frontend_reset_url,  # 将前端链接传入模板
            },
        }

在settings.py中指定自定义序列化器,并添加前端域名配置:

# settings.py
REST_AUTH_SERIALIZERS = {
    'PASSWORD_RESET_SERIALIZER': 'your_app.serializers.CustomPasswordResetSerializer',
}

# 配置前端域名
FRONTEND_DOMAIN = 'http://localhost:3000'

2. 创建自定义邮件模板

在项目templates/accounts/目录下新建password_reset_email.html模板,直接使用传入的前端链接:

<!-- templates/accounts/password_reset_email.html -->
你好,

请点击下方链接重置你的密码:
<a href="{{ frontend_reset_url }}">{{ frontend_reset_url }}</a>

若此操作非你本人发起,请忽略本邮件。

3. 前端处理密码重置流程

前端/new-password页面需完成以下操作:

  • 从URL中提取uid和token参数
  • 提供新密码输入框(含确认密码)
  • 提交时调用后端password/reset/confirm/接口,传入参数完成重置

示例前端请求(React/Next.js):

// 提交密码重置请求
const submitPasswordReset = async (uid, token, newPassword) => {
  try {
    const res = await fetch('http://localhost:8000/api/auth/password/reset/confirm/', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        uid,
        token,
        new_password1: newPassword,
        new_password2: newPassword,
      }),
    });
    const data = await res.json();
    if (res.ok) {
      console.log('密码重置成功');
      // 跳转登录页或提示用户
    } else {
      console.error('重置失败:', data);
    }
  } catch (err) {
    console.error('请求出错:', err);
  }
};

4. 验证后端路由配置

确保urls.py已包含dj_rest_auth的密码重置相关路由:

# urls.py
from django.urls import path, include

urlpatterns = [
    # 其他路由...
    path('api/auth/', include('dj_rest_auth.urls')),
    path('api/auth/password/reset/', include('dj_rest_auth.password_reset.urls')),
]

完成以上配置后,密码重置邮件中的链接将指向前端页面,用户在前端输入新密码后,通过调用后端接口完成最终的密码重置操作。

内容的提问来源于stack exchange,提问作者DroidT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 15:31:05