iFunction
iFunction

Reputation: 1268

Django dynamic links using multiple fields

I have a url set up dynamically for a project using:

path('project/<int:pk>', ProjectView.as_view(), name='project')

How can I make this so I can use two parameters, something like this:

path('project/<int:pk>/<int:category', ProjectView.as_view(), name='project')

So I need to set up links to each category, so the user will see only the updates from Project A category 1 of 7.

Upvotes: 1

Views: 157

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477190

If ProductView is a DetailView, you need to alter the get_queryset a bit, like:

from django.views.generic.detail import DetailView

class ProductView(DetailView):
    model = Product
    template = 'some_template.html'

    def get_queryset(self):
        return super().get_queryset().filter(
            category__id=self.kwargs['category']
        )

Here we thus will filter the queryset first by 'category', and the boilerplate code of the DetailView will then filter by the primary key pk.

In your templates, you can generate urls, with:

{% url 'project' pk=some_pk category=some_category_id %}

or if you for example redirect:

     return redirect('project', pk=some_pk, category=some_category_id)

Upvotes: 1

Related Questions