django-rest-auth 处理过期的确认邮件

django-rest-auth handling expired confirmation email

我在休息时使用 django-rest-auth 和 django-allauth 来处理用户身份验证 api。当用户在 link 过期后尝试验证他们的电子邮件时,我会收到一个令人不快的错误页面。

拜托,我怎样才能显示更好的错误页面或发送消息告诉他们由于 link 已过期而未成功?

编写您自己的自定义异常处理程序

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)

# Now add the HTTP status code to the response.
if response is not None:
    response.data['status_code'] = response.status_code

return response

据我所知,您的错误来自 django-allauth,而不是您的项目。错误的原因是您没有在主 urls.py 中包含 allauth.url(将在后面的部分中详细解释)。

可能的解决方案

第一个解决方案

在您的 urls.py 中添加 allauth.urls:

urlpatterns = [
    ...
    path('accounts/', include('allauth.urls')),
    ...
]

第二种解决方案

如果你深入研究这个问题,你会看到错误是说 NoReverseMatch 错误,当在项目中找不到 url 名称时会发生这种情况,即 account_login.现在此错误来自 allauth base template 处的模板。

根据您的代码判断,此错误的发生是由于以下行: (我冒昧地检查了您的 github 代码库,因为它是开源的。

if not email_confirmation:
    if queryset is None:
        queryset = self.get_queryset()
    try:
        email_confirmation = queryset.get(key=key.lower())
    except EmailConfirmation.DoesNotExist:
        # A React/Vue Router Route will handle the failure scenario
        return HttpResponseRedirect('/login/failure/')  # <-- Here

指向系统中不存在的错误url。请检查 django-rest-auth urls.

因此,这里的一个解决方法是在此处提供具有如下视图的模板响应:

# in accounts/api/urls.py
path('failure/', TemplateView.as_view(template_name='api_failure.html'))

另一种解决方案是像这样提供 custom 404 template

# accounts/api/views.py
def handler404(request, exception, template_name="your_custom_404.html"):
    response = render_to_response(template_name)
    response.status_code = 404
    return response

# root urls.py

 handler404 = 'accounts.api.views.handler404'