Hanny
Hanny

Reputation: 682

Django template with get_absolute_url() using args isn't working

Having trouble using get_absolute_url() with args to work in my template (perhaps I'm doing this incorrectly on the template side)

I keep getting an error that says person_id is not defined

I've got a simple model that looks like this:

class Course(models.Model):
    year = models.ForeignKey(Year, on_delete=models.PROTECT)
    name = models.CharField(max_length=50)
    short_name = models.CharField(max_length=50)
    created = models.DateTimeField(auto_now=False, auto_now_add=True)
    last_updated = models.DateTimeField(auto_now=True, auto_now_add=False)

It has get_absolute_url that looks like this:

    def get_absolute_url(self):
        """Return absolute url for Course."""
        return reverse(
            "view_course", args=[
                person_id, 
                location_id, 
                str(self.id)
            ]
        )

and I've got my URL which looks like this:

    path(
        "<person_id>/locations/<location_id>/course/<pk>/",
        views.CourseDetailView.as_view(),
        name="view_course",
    ),

In my template I've tried a few different ways to get this to display, currently it looks like this:

    {% for section in sections %}
        <a id="course{{section.course.id}}" href="{{person.id}}/locations/{{location.id}}/course/{{ section.course.get_absolute_url }}" class="card-link location-course-link">{{ location.person }}</a>{{section.course.short_name}}
    {% endfor %}

I have also tried: href="{{ section.course.get_absolute_url }}"

Also tried: href="{{ section.course.get_absolute_url person.id location.id }}"

While all the data is correct (the url comes out to 1/locations/3/course/5/ as expected in the template - it still gives that error when clicked on.

Upvotes: 1

Views: 257

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

You can not use get_absolute_url for that. The get_absolute_url method [Django-doc] has as purpose:

Define a get_absolute_url() method to tell Django how to calculate the canonical URL for an object. To callers, this method should appear to return a string that can be used to refer to the object over HTTP.

So that means the url is entirely determined by the object (through it fields, or through fields of related objects). But here there is, as far as I can see, no way to derive the person_id.

What you use the {% url … } template tag [Django-doc] to calculate the reverse url:

<a id="course{{section.course.id}}" href="{% url 'view_course' person.id location.id section.course.id %}" class="card-link location-course-link">{{ location.person }}</a>

Upvotes: 2

Related Questions