'Page not found after click in Django
I have a simple menu-list
{% block menu %}
<ul>
{% for item in list %}
<li><a href="{{item}}/">{{ item }}</a></li>
{% endfor %}
</ul>
{% endblock %}
and a list:
MENU = ['Home','Contact','About']
When I press Contact then go to the address 127.0.0.1:8000/Contact
with this same template but if I again click Contact I'm getting Page not found at 127.0.0.1:8000/Contact/Contact
What can I do about this?
Solution 1:[1]
The particular issue here is that the HTML you emit has links to "Contact/", which if you're already at a /Contact URL, will go to a /Contact/Contact like you see here.
The quick fix is to add a / right before the {{item}}, like this:
<li><a href="/{{item}}/">{{ item }}</a></li>
However, django has better ways to handle URLs than creating them yourself. Look at the URL dispatcher documentation [1], with the intention of being able to use the url template tag [2].
What that line would end up looking like then is something like this:
<li><a href="{% url item %}">{{ item }}</a></li>
Solution 2:[2]
Try changing href="{{item}}" to href="/{{item}}":
(% block menu %}
<ul>
{% for item in list %}
<li><a href="/{{item}}/">{{ item }}</a></li>
{% endfor %}
</ul>
{% endblock %}
You were using a relative URL which won't work if you're in a different level of the URL path.
Solution 3:[3]
Use absolute paths, for example:
MENU = [{'text':'Home',
'url':'/home'},
{'text':'Contact',
'url':'/contact'},
{'text':'Home',
'url':'/home'}]
And code like this:
{% block menu %}
<ul>
{% for item in list %}
<li><a href="{{url}}/">{{ text }}</a></li>
{% endfor %}
</ul>
{% endblock %}
But better solution would be to use some ready CMS app, for example from here django resources page like django-cms ( django-cms.org ).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrew |
| Solution 2 | Trey Hunner |
| Solution 3 | Qrees |
