Musical_Ant
Musical_Ant

Reputation: 67

getting unexpected/unwanted url path when clicking on an href link in django

so, here are all the urls i defined:

path("", views.index, name="index"),
path("login", views.login_view, name="login"),
path("logout", views.logout_view, name="logout"),
path("register", views.register, name="register"),
path("new", views.new.as_view(), name="new"),
path("<int:user>/watchlist", views.watchlist, name="watchlist"),
path("<int:user>/<str:name>", views.name, name="name"),
path("<str:user>/<str:name>/watchlist/remove", views.remove, name="remove-from-watchlist"),
path("<int:user>/<str:name>/watchlist/add", views.add, name="add-to-watchlist"),
path("<str:user>/<str:name>/bid", views.bid, name="bid"),
path("<str:user>/<str:name>/close", views.close, name="close-bid"),
path("<str:user>/<str:name>/comment", views.comment, name="comment"),
path("add-category", views.addC, name="add-Category"),
path("categories", views.categories, name="categories"),
path("<str:cat>/category", views.cat, name="category-page")

From experience, the problem is with all the 'watchlist' related URLs. For example, when i am on index view, the path to path("<int:user>/watchlist", views.watchlist, name="watchlist"), is <a class="nav-link" href="{{ user.id }}/watchlist">Watchlist</a> and the url path shows the same -

http://127.0.0.1:8000/2/watchlist where 2 is the user id. Then when i go to a url <a class="nav-link" href="categories">Categories</a> the url path followed is http://127.0.0.1:8000/2/categories the '2' should not be there! I specifically hard coded the path in the anchor tag

I am facing another problem: when i am at the index view and i click on the anchor tag containing <a href=/{{ user.id }}/{{ item.Title }} where item.Title is say "Magic Broom", the url path i am getting is

http://127.0.0.1:8000/2/Magic while it should have been http://127.0.0.1:8000/2/Magic Broom

Can someone please explain what's going on here...

Upvotes: 0

Views: 474

Answers (1)

Razenstein
Razenstein

Reputation: 3717

the correct reverse for the path would be like this:

path("<int:user>/watchlist", views.watchlist, name="watchlist")


<a href="{% url 'watchlist' user=xyz %}"> some text </a>

In your example you built the url "manually" instead you should always go reverse via path->name definition which is done by the {% url ... %}. Why? if your urls change you only have to update paths in the settings.py

Upvotes: 2

Related Questions