使用dj-rest-auth时无法在密码重置邮件模板获取uid和key求助
解决方案
方法一:自定义密码重置序列化器(推荐)
dj-rest-auth 默认的密码重置邮件上下文未传入 uid 和 key,仅提供了 password_reset_url。我们可以通过重写密码重置序列化器,手动将这两个参数注入邮件上下文:
- 在你的项目应用中创建
serializers.py,编写自定义序列化器:
from dj_rest_auth.serializers import PasswordResetSerializer from django.contrib.auth.tokens import default_token_generator from django.utils.http import urlsafe_base64_encode from django.utils.encoding import force_bytes class CustomPasswordResetSerializer(PasswordResetSerializer): def get_email_options(self): user = self.get_user(self.data.get('email')) if user: # 生成与默认逻辑一致的uid和key uid = urlsafe_base64_encode(force_bytes(user.pk)) key = default_token_generator.make_token(user) return { 'extra_email_context': { 'uid': uid, 'key': key, }, } return super().get_email_options()
- 在
settings.py中配置 dj-rest-auth 使用该自定义序列化器:
REST_AUTH_SERIALIZERS = { 'PASSWORD_RESET_SERIALIZER': 'your_app_name.serializers.CustomPasswordResetSerializer', }
- 现在你可以在
password_reset_key_message.txt模板中直接使用参数:
请点击以下链接重置密码: https://fontend-project.com/password-reset?id={{ uid }}&key={{ key }}
方法二:解析默认的 password_reset_url 提取参数
如果不想修改序列化器,可以通过解析默认生成的重置链接来提取 uid 和 key,但这种方法依赖链接结构,稳定性稍差:
- 在应用的
templatetags目录下创建reset_url_filters.py(若没有该目录则新建):
from django import template from urllib.parse import urlparse register = template.Library() @register.filter def extract_uid(reset_url): parsed = urlparse(reset_url) # 默认重置链接路径格式为 /reset/<uidb64>/<token>/,分割后取对应部分 path_segments = parsed.path.strip('/').split('/') return path_segments[1] if len(path_segments) >= 2 else '' @register.filter def extract_key(reset_url): parsed = urlparse(reset_url) path_segments = parsed.path.strip('/').split('/') return path_segments[2] if len(path_segments) >= 3 else ''
- 在模板中加载过滤器并使用:
{% load reset_url_filters %} 请点击以下链接重置密码: https://fontend-project.com/password-reset?id={{ password_reset_url|extract_uid }}&key={{ password_reset_url|extract_key }}
补充说明
django-allauth 的邮箱确认邮件上下文默认包含 uid 和 key,但 dj-rest-auth 的密码重置模块并未默认传入这两个参数,因此需要通过上述方法手动添加或提取。
内容的提问来源于stack exchange,提问作者TomásVF
相关产品推荐
相关产品推荐

