[Answered ]-Django html href query last object pass id to url tag

1👍

✅

We can store the last object and then use that in the URL:

<div class="top-button-container stickey-top">
  {% with last=cast.objects.last %}
    {% if last.enddate %}
      <button type="button" class="btn btn-danger btn-lg btn-block"><a class="nav-link" href="{% url 'caststart' %}">Start Cast</a>
       </button>
    {% else %}
      <button type="button" class="btn btn-danger btn-lg btn-block">
                <a class="nav-link" href="{% url 'castend' last.pk %}">End Cast</a></button>
    {% endif %}
  {% endwith}
</div>

but this all look bad code design: making custom queries in the template and writing business logic in the template is often not a good idea.

How do I pass the pk of the last object in the cast model to the href url tag?

Yes, that’s the tricky bit. I would not do this that way. We can separate concerns here. We can make two views, one that redirects to the latest item, and one that then makes a form to edit an arbitrary id, so:

urlpatterns = [
    # …
    path('casts/end/', views.cast_end, name='cast-end'),
    path('casts/<int:id>/edit/', views.cast_edit, name='cast-edit'),
    # …
]

with cast_end a simple view:

from django.shortcuts import redirect


def cast_end(request):
    last = Cast.objects.latest('pk')
    return redirect('cast-edit', id=last.pk)

so the view itself will make a redirect to plug in the latest object.

Then the template is just:

<a href="{% url 'cast-end' %}">

Leave a comment