Elcid_91
Elcid_91

Reputation: 1681

How to place links in django templates

VERY new to Django and I am a little confused. I have placed a link in my html template file; however, clicking the link reports a 404 error.

App views.py file:

from django.shortcuts import render        

def index(request):
    return render(request, "login/index.html", None)

def terms(request):
    return render(request, "login/terms.html", None)

App urls.py:

from django.urls import path   
from . import views

urlpatterns = [
    path('', views.index, name="index"),
    path('', views.terms, name="terms")
]

Offending code in index.html:

By signing in, you agree to our <a href="/login/terms.html">Terms Of Use Policy</a>

Clicking on the link pops a 404 error. Any help would be appreciated as I learn a new framework.

Upvotes: 3

Views: 4963

Answers (2)

Arjun Shahi
Arjun Shahi

Reputation: 7330

urlpatterns = [
    path('', views.index, name="index"),
    path('terms/', views.terms, name="terms")
]
By signing in, you agree to our <a href="{% url 'terms' %}">Terms Of Use Policy</a>
or

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

The first problem is that both the path to the views.index and views.terms share the same path. As a result, you have made views.terms inaccessible.

You thus should change one of the paths, for example:

from django.urls import path   
from . import views

urlpatterns = [
    path('', views.index, name='index'),
    path('terms/', views.terms, name='terms')
]

You better use the {% url ... %} template tag [Django-doc] to resolve the URLs, since if you later decide to change the path of a certain view, you can still calculate the path.

In your template, you thus write:

By signing in, you agree to our <a href="{% url 'terms' %}">Terms Of Use Policy</a>

Upvotes: 5

Related Questions