【发布时间】:2019-06-15 12:25:11
【问题描述】:
我发现了许多与此问题类似的问题。 This question 是其中之一,但它并没有解决我的问题,所以我会问我自己的问题。
我正在我的网站上制作密码重置页面。但是当我转到http://localhost:8000/users/reset-password 并输入我的电子邮件并单击“重置我的密码”时,Django 会向我抛出一个NoReverseMatch 错误。
错误是:
NoReverseMatch at /users/reset-password/
Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name.
我认为我编写 urlpatterns 的方式有问题。
我试过了:
- 制作我自己的视图和模板。
- 重写我所有的 urlpatterns。
我的代码
urls.py:
"""Defines URL Patterns for users."""
from django.urls import re_path
from django.contrib.auth.views import (
LoginView, PasswordResetView, PasswordResetConfirmView,
PasswordResetDoneView,
)
from . import views
urlpatterns = [
# Login Page.
re_path(r'^login/$', LoginView.as_view(template_name='users/login.html'),
name='login'),
# Logout Page.
re_path(r'^logout/$', views.logout_view, name='logout'),
# Registration Page.
re_path(r'^register/$', views.register, name='register'),
# Password reset Page.
re_path(r'^password_reset/$', PasswordResetView.as_view(
# This is the only line I added in this file.
template_name='users/password_reset_email.html'
),
name='password_reset'),
# Password reset done Page.
re_path(r'^password_reset/done/$', PasswordResetDoneView.as_view(),
name='password_reset_done'),
# Password reset confirm Page.
re_path(r'^password_reset/confirm/'
+ '(?P<uidb64>[0-9A-Za-z]+)/(?P<token>.+)/$',
PasswordResetConfirmView.as_view(),
name='password_reset_confirm'),
]
我的自己的 users/password_reset_email.html:
{% load i18n %}{% autoescape off %}
{% blocktrans %}You're receiving this email because you requested a password reset for your user account at {{ site_name }}.{% endblocktrans %}
{% trans "Please go to the following page and choose a new password:" %}
{% block reset_link %}
{{ protocol }}://{{ domain }}{% url 'users:password_reset_confirm' uidb64=uid token=token %}
{% endblock %}
{% trans "Your username, in case you've forgotten:" %} {{ user.get_username }}
{% trans "Thanks for using our site!" %}
{% blocktrans %}The {{ site_name }} team{% endblocktrans %}
{% endautoescape %}
更新:
我做对了。现在我得到一个NoReverseMatch at /users/password_reset/
Reverse for 'password_reset_confirm' with keyword arguments '{'uidb64': '', 'token': ''}' not found. 1 pattern(s) tried: ['users/password_reset/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$']。我使用我的 djangos password_reset_email.html 的 own 模板遇到了这个错误,我在其中修改了行:{% url 'password_reset_confirm' uidb64=uid token=token %} 到 {% url 'users:password_reset_confirm' uidb64=uid token=token %}。现在我几乎可以肯定我只是写错了我的网址或正则表达式。
我已编辑我的问题以显示新代码。
【问题讨论】:
-
您是否将这些 urlpatterns 包含到主要 urlpatterns 中?
-
是的,在我的项目文件夹中,我已经包含了所有以 /users/ 开头的 url 像这样:
re_path(r'^users/$', include(('users.urls', 'users'), namespace='users'))
标签: python django django-authentication