Search code examples
djangohref

django 1.11 html "href" doesn't work with template url


My urls.py

urlpatterns = [
url(r'^index', views.index, name='index'),

my views.py

def index(request):
return render(request, 'index.html', {})

index.html

<ul>
<li><a href="{% url 'all_contacts' %}"></a>All Contacts</li>
</ul>

My page with the href hyperlink not working

enter image description here

The source:

enter image description here

So I had a look at https://www.w3schools.com/tags/att_a_href.asp and it indicates that relative paths only work if it's pointing to a file. Not sure what I'm missing here?


Solution

  • Here:

    <a href="{% url 'all_contacts' %}"></a>All Contacts
    

    Your <a> tag is empty. You want to put the link text inside the tag:

    <a href="{% url 'all_contacts' %}">All Contacts</a>
    

    Oh and while we're at it:

    I had a look at https://www.w3schools.com/tags/att_a_href.asp and it indicates that relative paths only work if it's pointing to a file

    The exact text is: "A relative URL - points to a file within a web site (like href="default.htm")". But that's still complete BS, there's no notion of file here, a "relative url" (actually an absolute or relative path) is resolved against the current domain (and the current path if it's a relative path), how the resulting url is served depends on the software serving this resource. FWIW, Django's urls (the one built by the {% url %} tag) are always absolute path.