Search code examples
djangourldjango-templatesurl-routing

How to pass a value to a urlpattern using django templating?


So I have this urlpattern where we could type a number on the address bar and it will render an html template which will display the entered number on the page, I decided to give it a little more functionality by piping an add:1 to a links href so that every time we click on the link it adds up to the previous number and then generate the response by displaying that number on the page, But I can't get it to work using django templating I keep getting page not found 404 error, Can anyone please help me with this? Here's is the url pattern which accepts an integer

urlpatterns = [
        path('home/<int:num>',views.index,name='index')
        ]

Here's the HTML template

<!DOCTYPE html>
<html>
    <head>
        <title>Dynamic urls</title>
    </head>
    <body>
        <h1>Page no. {{num}}</h1>
        <a href="{url 'home/{{num|add:1}}' }">Change the page</a>
    </body>
</html>

Solution

  • the right way is to combine with statment with add filter before passing the new calculated variable to url as second parameter.

    {% with num_=num|add:1 %}
      <a href="{% url 'home' num=num_ %}">Change the page</a>
    {% endwith %}
    

    PS

    • there should be NO spaces around =
    • variables should NOT start with _
    • usual math ops (+) are NOT allowed just filters like add