Edmund Liang
Edmund Liang

Reputation: 51

creating a hyperlink in django using href

I tried to copy the way this django tutorial did their hyperlinks for my own project: https://docs.djangoproject.com/en/3.0/intro/tutorial01/.

However, on my screen, I do not have hyperlinks, just regular text. What I currently have in my index is a bunch of names of units, and I want the user to be able to click on that unit to get a more detailed view of that unit's information. This is what I currently have in my templates, views, and urls:

urls:

from django.urls import path

from . import views

app_name = 'calc'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.UnitView.as_view(), name='unit'),
]

views:

from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from django.shortcuts import render
from django import forms
from .models import Unit, Class

# Create your views here.

class IndexView(generic.ListView):
    template_name = 'calc/index.html'
    context_object_name = 'unit_list'

    def get_queryset(self):
        return Unit.objects.all()

class UnitView(generic.DetailView):
    model = Unit
    template_name = 'calc/unit.html'

index.html:

{% if unit_list %}
    <ul>
    {% for unit in unit_list %}
        <li><a href="{% url 'calc:unit' unit.id %}"></a>{{ unit.unit_name }}</li>
    {% endfor %}
    </ul>
{% else %}
    <p>No units are available.</p>
{% endif %}

unit.html:

{{unit.unit_class}}

My guess is that either I'm using href incorrectly, or my urls.py is incorrect.

Upvotes: 1

Views: 8031

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32244

You need to put {{ unit.unit_name }} inside the <a> tag

The contents of an <a> tag are what get rendered as the link

<a href="{% url 'calc:unit' unit.id %}">{{ unit.unit_name }}</a>

Upvotes: 2

Related Questions