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

Django后端找回密码邮件功能问题及405错误求助

Django找回密码功能问题排查与解决

一、找回密码邮件未收到且无报错的排查方向

  • 验证SMTP配置有效性:在终端执行python manage.py shell,运行以下测试代码直接验证邮件发送功能:
    from django.core.mail import send_mail
    send_mail('测试邮件', '这是一封测试邮件', '你的Gmail邮箱', ['接收测试的邮箱'], fail_silently=False)
    
    若执行报错,根据错误信息修正SMTP配置;若执行成功但未收到邮件,检查接收邮箱的垃圾邮件文件夹。
  • 确认环境变量加载:确保config("EHU")和config("EHP")正确读取到你的Gmail邮箱地址和应用密码,可临时在settings.py中硬编码邮箱信息进行测试(测试后记得改回)。
  • 检查Gmail账号设置:确认你的Gmail账号已开启两步验证,且生成的应用密码正确无误;同时确保账号未限制SMTP服务访问。
  • 核对超级用户邮箱:通过shell查询数据库中超级用户的邮箱是否与你输入的一致:
    from django.contrib.auth.models import User
    print(User.objects.get(is_superuser=True).email)
    

二、PasswordResetCompleteView提交新密码返回405错误的解决方法

405错误的核心原因是:PasswordResetCompleteView仅处理GET请求,它是用来显示密码重置完成的页面,提交新密码的动作应该由PasswordResetConfirmView处理。以下是具体修复步骤:

1. 修正URL路由配置

确保路由规则正确映射视图,PasswordResetConfirmView必须包含<uidb64>/<token>参数用于验证重置请求,示例配置如下:

from django.urls import path
from .views import (
    PasswordChangePageView,
    PasswordResetConfirmViewPage,
    PasswordResetCompleteViewPage
)

urlpatterns = [
    path('password-reset/', PasswordChangePageView.as_view(), name='password_reset'),
    path('password-reset-confirm/<uidb64>/<token>/', PasswordResetConfirmViewPage.as_view(), name='password_reset_confirm'),
    path('password-reset-complete/', PasswordResetCompleteViewPage.as_view(), name='password_reset_complete'),
]

2. 完善PasswordResetConfirmViewPage配置

显式设置success_url,确保密码重置成功后正确重定向到完成页面:

class PasswordResetConfirmViewPage(PasswordResetConfirmView):
    template_name = "password_reset_confirm.html"
    success_url = reverse_lazy("password_reset_complete")  # 对应路由中设置的name

3. 修正模板表单提交地址

检查password_reset_confirm.html中的表单,确保表单以POST方式提交到当前URL(无需手动设置action):

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">重置密码</button>
</form>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 16:52:54