[Fixed]-Django url – No reverse match

1👍

Django is not able to reverse the use of a | character outside of a capturing group. However, I highly doubt you need it here.

Django always matches the first slash of the url, so there’s no need to match the starting slash in your regex. Adding a starting slash would only match a second slash at the start of your url. Unless you want the url path to be example.com//vieworder/1/ rather than example.com/vieworder/1/, you should just remove the slash from your pattern.

Since the first slash is already matched by Django, and there’s nothing else between the first slash and the vieworder/1/ part, you can just leave the include pattern empty:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', include('main.urls')),
]

This will match the url example.com/vieworder/1/, and allow Django to reverse the url.


As for your second problem:

You need to make the outer group a non-capturing group with ?::

url(r'^vieworder(?:/(?P<order_id>\d+))*/$', views.vieworder, name='vieworder'),

Django will substitute the outermost capturing group, which in this case should contain /1 instead of 1. By making it a non-capturing group, Django will substitute the argument 1 into the inner group instead of the outer group.

👤knbk

Leave a comment