Django 第三方库 url 模式在自定义 url 模式之前?(网址模式顺序)



使用Django(REST Framework)这是我的根网址:

... (imports)
urlpatterns = [
re_path(r"^confirm-email/(?P<key>[-:w]+)/$", accounts_views.email_verification,
name="account_confirm_email"),
path('admin/', admin.site.urls),
path('request/', include('request.urls')),
path('rest-auth/', include('rest_auth.urls')),
path('rest-auth/registration/', include('rest_auth.registration.urls')),
re_path(r'^account-confirm-email/', TemplateView.as_view(),
name='account_email_verification_sent'),
]

现在,我正在使用django-rest-auth库进行身份验证。此库在用户提交注册表后向用户发送电子邮件,以激活用户的电子邮件地址。

这封电子邮件中有一个链接,它是通过反转 url 模式获得的,网址模式名为:account_confirm_email

Django-rest-auth 库附带了它自己的名为account_confirm_email的 URL 模式,准确地说,在以下文件中:

python3.7/site-packages/rest_auth/registration/urls.py:

... (imports)
urlpatterns = [
...
url(r'^account-confirm-email/(?P<key>[-:w]+)/$', TemplateView.as_view(),
name='account_confirm_email'),
]

我希望我自己的 url 模式是相反的,而不是其余身份验证的模式,因为我的模式是按顺序排在第一位的。正如 Django 文档所述:

Django 按顺序运行每个 URL 模式,并在第一个停止 一个与请求的 URL 匹配的 URL。

https://docs.djangoproject.com/en/2.2/topics/http/urls/

但在实践中,rest-auth 模式是被颠倒的模式,为什么会发生这种情况?

为了完整起见,我看到 Django 文档还说:

Django 确定要使用的根 URLconf 模块。通常,这是 ROOT_URLCONF设置的值,但如果传入的 HttpRequest 对象有一个 urlconf 属性(由中间件设置),其值将是 用于代替ROOT_URLCONF设置。

https://docs.djangoproject.com/en/2.2/topics/http/urls/

django-rest-auth 是否做了上面引用的 Django 文档中描述的内容?如果是这样,在 django-rest-auth 的模式之前,我自己的 url 模式是否仍然可以反转?(我该怎么做?

它应该以这种方式运行,因为你编写的 URLPattern 将与通过django-rest-auth库发送的电子邮件中存在的 URL 不匹配。

替换此行:

re_path(r"^confirm-email/(?P<key>[-:w]+)/$", accounts_views.email_verification, name="account_confirm_email"),

为此:

re_path(r"^account-confirm-email/(?P<key>[-:w]+)/$", accounts_views.email_verification, name="account_confirm_email"),

最新更新