首页 > 解决方案 > django-rest-auth handling expired confirmation email

问题描述

I am using django-rest-auth and django-allauth to handle user authentication in my rest api. When a user tries to verify their email after the link has expired, I get an unpleasant error page.

enter image description here

Please, how can I display a better error page or send a message telling them it wasn't successful because the link had expired?

标签: djangodjango-rest-frameworkdjango-allauthdjango-rest-auth

解决方案


据我了解,您的错误来自django-allauth,而不是来自您的项目。错误的原因是你没有包含allauth.url在你的 main 中urls.py(将在后面的部分中解释更多)。

可能的解决方案

第一个解决方案

添加allauth.urls你的urls.py

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

第二种解决方案

如果你深入研究这个问题,你会看到错误是说NoReverseMatch错误,当在项目中找不到 url 名称时会发生这种情况 ie account_login。现在这个错误来自 at 的模板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'

推荐阅读