Reputation: 313
Okay, to be clear I've searched and read, followed the official docs, tried multiple solutions from SOF, nothing seems to be working so I have to resort to shamefully asking for help.
I'm simply trying to generate urls the proper way.
root urls.py:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'|/', include('main.urls')),
]
urls.py:
app_name = 'main'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^vieworder/(?P<order_id>[0-9]+)/$', views.vieworder, name='vieworder'),
]
template file:
<td><a href="{% url 'main:vieworder' order.id %}">View</a></td>
also tried:
<td><a href="{% url 'main:vieworder' order_id=order.id %}">View</a></td>
Error:
Reverse for 'vieworder' with arguments '(1,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['|/vieworder/(?P<order_id>d+)/$']
I don't understand why this is not working. I tested the regex against vieworder/1/ in a regex tester and it works fine. Django even tells me in the error that it tried the correct url pattern, however the error really isn't very clear on what is actually wrong.
Upvotes: 0
Views: 1425
Reputation: 53719
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.
Upvotes: 1