TheMeaningfulEngineer
TheMeaningfulEngineer

Reputation: 16359

Django link gets appended to URL

I'm using Django for a project, and am trying to make a link to a page called "index" which is the starting page from the page with an url

http://localhost:8000/index/result

I've added the link like this:

<a href="index">Start over </a>

As a result,the link directs to:

http://localhost:8000/index/result/index

instead of the required:

http://localhost:8000/index

I have all the pages set in urls.py and views.py.

Any help is appreciated. tnx

Upvotes: 3

Views: 2528

Answers (2)

supervacuo
supervacuo

Reputation: 9262

To build on Daniel Roseman's correct answer, this is nothing to do with Django; you'd experience this issue with plain HTML.

Adding / at the start of a URL as Daniel is suggesting (or specifying a protocol) turns it into an absolute link. Starting with an arbitrary name causes the browser to treat it as a relative link. There's a lot out there explaining the difference, but it's actually pretty simple. Assuming you have the following files:

/var/www/html/
├── directory/
│   └── three.html
├── two.html
└── one.html

Then you could link to the other pages from one.html like

<a href='two.html'>2</a>
<a href='directory/three.html'>3</a>

or

<a href='/two.html'>2</a>
<a href='/directory/three.html'>3</a>

And you can link to other pages from three.html like

<a href='../one.html'>2</a>
<a href='../two.html'>2</a>

(../ means "go up one level).

or

<a href='/one.html'>2</a>
<a href='/two.html'>2</a>

So when you make a Django template with a link like <a href="index">Start over</a>, it adds the href value to the URL of the current page, treating it like a relative link.

Upvotes: 5

Daniel Roseman
Daniel Roseman

Reputation: 599856

<a href="/index">Start over </a>

or even better

<a href="{% url "index" %}">Start over </a>

Upvotes: 9

Related Questions