简体   繁体   中英

Django third party library url pattern before custom url pattern? (url pattern order)

Using Django (REST Framework) this is my root 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'),
]

now, I am using the django-rest-auth library for authentication. This library sends a email to the user after they submit the registration form, for the purpose of activating the user's email address.

In this email is a link, which is obtained by reversing an url pattern, the url pattern named: account_confirm_email

the django-rest-auth library comes with it's own url pattern named account_confirm_email , in the following file, to be precise:

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'),
]

I expect my own url pattern to be the one that is reversed , not the rest-auth one, since mine comes first in order. As the Django docs state:

Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.

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

But in practice the rest-auth pattern is the one that is being reversed, why does this happen?

To be complete, I see that the Django docs also say:

Django determines the root URLconf module to use. Ordinarily, this is the value of the ROOT_URLCONF setting, but if the incoming HttpRequest object has a urlconf attribute (set by middleware), its value will be used in place of the ROOT_URLCONF setting.

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

Does django-rest-auth do what is being described in the above quote of the Django docs? And if so, is it still possible to have my own url pattern be reversed before django-rest-auth's pattern? (And how would I do that?)

It is expected to behave that way , because the URLPattern that you wrote will not match the URL present in the email sent through django-rest-auth library.

Replace this line:

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

For this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM