Search code examples
pythondjangocoding-styleurl-routing

django strange warning for urlconf


Django behaves as I hoped and expected, but gives me a warning. It seems my use-case was not thought about. Which confuses me, so my question: do I miss any problems waiting for me, or did the developers miss this use case.

I want the url person/<slug>/ to point to a detail view, and the url persons/ to point to the list view. It is more human-readably-correct than beginning with persons/ in the detail view too. I use include to make the code neater, something like:

url(r'^person', include([ 
    url(r'^s/$', views.foo),
    url(r'^/(?P<slug>[\w-]+)/form/$', views.form),
    url(r'^/(?P<slug>[\w-]+)/$', views.bar),
])),

Now Django tells me, that the slash at the beginning is unneccesary - which is wrong, leaving it out leaves me with reversed urls person<slug> with no slash in between. I do not see why this should be bad style. The warning is:

WARNINGS:
?: (urls.W002) Your URL pattern '^/(?P<slug>[\w-]+)/form/$'
[name='person_form'] has a regex beginning with a '/'. Remove this 
slash as it is unnecessary. If this pattern is targeted in an 
include(), ensure the include() pattern has a trailing '/'.

Solution

  • In your case, the warning is a false positive, but it's a fairly unusual use case, so I don't think that the heuristic in Django necessarily has to be changed.

    You could prevent the warning by changing the URL patterns to:

    url(r'^persons/$', views.foo),
    url(r'^person/', include([ 
        url(r'^(?P<slug>[\w-]+)/form/$', views.form),
        url(r'^(?P<slug>[\w-]+)/$', views.bar),
    ])),
    

    At first, the warning was for any URLs that started with a / (ticket 23813). Then, it was pointed out that there were some cases where it is valid to use a slash, so the warning was disabled when settings.APPEND_SLASH = False (ticket 27238).

    If you think the check should be amended (or even removed) then the django-developers mailing list or ticket tracker would be a better place to discuss this than Stack Overflow.