pythondjangodjango-viewsdjango-urlsurl-pattern

How can I personalize an URL path in Django?


I am trying to build an website which renders some books and the corresponding pages. I want to make possible to access a page like this:

path('/<str:book_pk>-<int:book_page>/', views.TestClass.as_view(), name='book-test')

I want a user to access it very simple, something like: mysite.com/5-12/ - which redirects him to the book nr 5 at page 12. The problem is that when I access this page from the website itself, using href, the real path becomes:

mysite.com/%2F5-13/

If I want to write in the browser, the following path: myste.com/5-13/, it throws me 404 page not found, because the real path is mysite.com/%2F5-13/ . This is pretty obvious, but my question is:

How can I stick to my initial path, and make it possible to be accessed via myste.com/5-13/? For some reason, Django URL Patterns, adds an extra %2F string at the beginning. Can somebody explain me why, and how to solve this issue?

I much appreciate your time and effort! Thank you so much!


Solution

  • You don't have to include / at the beginning of the url, simply:

    path('<str:book_pk>-<int:book_page>/', views.TestClass.as_view(), name='book-test')
    

    / is encoded automatically as %2F in urls (read the full list here)