Kubas
Kubas

Reputation: 1028

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?

Upvotes: 1

Views: 3020

Answers (3)

Trey Hunner
Trey Hunner

Reputation: 11814

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.

Upvotes: 1

Andrew
Andrew

Reputation: 3332

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>
  1. [1] http://docs.djangoproject.com/en/dev/topics/http/urls/
  2. [2] http://docs.djangoproject.com/en/1.2/ref/templates/builtins/#url

Upvotes: 6

Qrees
Qrees

Reputation: 36

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 ).

Upvotes: 0

Related Questions