Being able to encode url parameters in django template while using url tag to prevent NoReverseMatch error

I'm writing a project with python 3.10 and django 4.1

I defined the following route:

app_name = 'admin_extend'

urlpatterns = [
    path('add_fav/<str:name>/<str:add_url>/<str:admin_url>/', views.add_fav, name='add_fav'),
]

now i have 3 parameters here, name, add_url and admin_url.

both add_url and admin_url contains '/' so i need to be able to escape them in the django template.

this is my code in the template:

<a href="{% url 'admin_extend:add_fav' name=model.name add_url=model.add_url admin_url=model.admin_url %}" class="changelink">{% translate 'Fav' %}</a>

lets say the parameters value are name='foo', add_url='/a/b/c/', admin_url='/c/d/e/', the route fails with NoReverseMatch:

Reverse for 'add_fav' with keyword arguments '{'name': 'foo', 'add_url': '/a/b/c/', 'admin_url': '/c/d/e/'}' not found. 1 pattern(s) tried: ['admin_extend/add_fav/(?P<name>[^/]+)/(?P<add_url>[^/]+)/(?P<admin_url>[^/]+)/\\Z']

i tested it and if i provide the parameters without / characters then i get no error.

my problem is i really can't find anywhere how to escape these parameters, i googled and checked on stackoverflow a lot

for example i can't use the {% filter urlencode %} before and after because the url needs to be validated first and then it will go through the urlencode,

i learned that i can't run python code in these templates so i can't use urlqoute from django.utils.http

and using urlencode filter in this way is not a correct syntax:

{% url 'admin_extend:add_fav' name=(model.name|urlencode) add_url=(model.add_url|urlencode) admin_url=(model.admin_url|urlencode) %}

how can I resolve this ?

thanks

Back to Top