Django: how can I generate reverse urls including numbers in the string?

2259 views django

I´m using the following code to generate urls:

url(r'^productos/(?P<person_id>\D+)/$', views.ProductoView, name="producto"),

It works fine with strings that only have letters (dTape).

When I try a string that includes a number (d3Tape) I get a nonreverse error.

Any clues? Maybe my regex is not ok but I can´t find the solution.


answered question

1 Answer


You can include all characters by using a character group that includes both \d and \D:

url(r'^productos/(?P<person_id>[\d\D]+)/$', views.ProductoView, name="producto"),

But I'm not sure if this is a good idea. It might be useful to restrict the caracters to a group, like:

url(r'^productos/(?P<person_id>[A-Za-z0-9_-]+)/$', views.ProductoView, name="producto"),

this will include all ASCII alphanumerical characters and a hyphen and underscore.

In , I would advise to use the str, or slug path converters:

path('productos/<str:person_id>/', views.ProductoView, name="producto"),

posted this

Have an answer?


Please login first before posting an answer.