首页 > 解决方案 > 自定义 url 模式之前的 Django 第三方库 url 模式?(网址模式顺序)

问题描述

使用 Django(REST 框架),这是我的根 url conf:

... (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 模式获得的,该 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 模式是反转的,而不是 rest-auth 的,因为我的排在第一位。正如 Django 文档所述:

Django 按顺序遍历每个 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 模式?(我该怎么做?)

标签: pythondjangodjango-rest-frameworkdjango-rest-auth

解决方案


预计会以这种方式运行,因为您编写的 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"),

推荐阅读