Question: Django url warning urls.W002

Question

Django url warning urls.W002

Answers 3
Added at 2017-01-03 19:01
Tags
Question

Sorry in advance if this question look a bit superfluous but is something that is really bothering me.

I have a set of API's written in Django defined by the following urls.

# urls.py
import ...
urlpatterns = [
    url(r"^api/v1/account", include(profile.urls))
]

and

# profile/urls.py
import ...
urlpatterns = [
    url(r"^$", AccountAPI.as_view()),
    url(r"^/login$", LoginAPI.as_view()),
    url(r"^/logout$", LogoutAPI.as_view())
]

This configuration should allow only the urls:

/api/v1/account
/api/v1/account/login
/api/v1/account/logout

This work for my purpose but I keep having warnings like(I have several API defined with this rule and the warning list is way bigger):

?: (urls.W002) Your URL pattern '^/login$' has a regex beginning with a '/'. Remove this slash as it is unnecessary.
?: (urls.W002) Your URL pattern '^/logout$' has a regex beginning with a '/'. Remove this slash as it is unnecessary.

If I remove the slash the server will not validate the urls I defined. For that I have to had a slash to the first level of the urls like:

# urls.py
import ...
urlpatterns = [
    url(r"^api/v1/account/", include(profile.urls))
]

And this will make the account call to end with a slash, something I don't want to.

I feel that I have defined the urls the most elegant way I found to serve my purpose and I keep having this sad warnings in my logs.

Am I doing something wrong? Is there a right way to define the url's without compromising the structure I choose for them? Or there's a way of turning this warnings off?

Answers
nr: #1 dodano: 2017-01-03 19:01

When I wrote the check, I incorrectly assumed urls with trailing slashes, like /api/v1/account/ and /api/v1/account/login/.

If you do not use trailing slashes, then starting an included url pattern with ^/ can be correct, and the W002 check gives a false positive.

As of Django 1.10.2, the check is disabled if you have APPEND_SLASH=False in your settings. See ticket 27238 for the discussion.

nr: #2 dodano: 2017-01-03 19:01

You can turn the warning(s) off using SILENCED_SYSTEM_CHECKS option.

Example:

SILENCED_SYSTEM_CHECKS = ['urls.W002', 'security.W019']
nr: #3 dodano: 2017-01-03 19:01

this will make the account call to end with a slash, something I don't want to.

Why? Is there any specific reason?

As far as Django is concerned, there's nothing incorrect in ending a url with a slash. Moreover, Django's admin urls end in a slash. Django polls tutorial also appends slash to root URLconfs.

If you read URL Dispacher example, it says:

There’s no need to add a leading slash, because every URL has that. For example, it’s ^articles, not ^/articles.

Source Show
◀ Wstecz