Use the url as a variable in my jinja2 template?

Viewed 248

Is a way to use the slug in my template?

I have in my urls:

path("cats/check/<int:pk>/lista", ObjetoListView.as_view(), name='posesiones_consulta'),

How can I access int:pk as a variable?

I want to evaluate this:

{% if cat.mom.id == pk %} 
1 Answers

You pass it to the context with:

class ObjectoListView(ListView):

    # …

    def get_context_data(self, *args, **kwargs):
        return super().get_context_data(
            *args,
            pk=self.kwargs['pk'],
            **kwargs
        )

If you however want to filter the list, you should do this at the database level, for example with:

class ObjectoListView(ListView):

    # …

    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(
            mom__pk=self.kwargs['pk']
        )

It is not a good idea to filter in the template, since then the database will return all records and thus increase the bandwidth between the database and the application, and furthermore filtering at the database level is (nearly) always faster than filtering in the view or template.

Related