Search code examples
djangodjango-viewsdjango-tables2

Click on row in django-tables2 to take me to another table?


I basically want to click on a row or linked element and take me to another filtered table.

For instance, let's say I have a table of genres:

Romance
Horror
Comedy

I click on Romance, and then I want a list of all the romance books. How might I do this with django-tables2?

How do I get what the user clicked on in my django table?

I tried to use table.py

class GenreTable(tables.Table):
     genre = tables.LinkColumn('books_genre_table')
     class Meta: ...

This doesn't work because I can't pass the data and filter it to make a table in the next view/html 'books_genre_table.html'

EDIT: I already have a detail page for genres that is different than this page that I want to create. Furthermore, I want to filter the data in a new way that does not need to be saved as a detail page with a 'pk'. I just want to have all of these go to one url.


Solution

  • Lets say you have a genre URL like this:

    path('some_path/<int:pk>/', genre_book_view, name='books_genre_table')
    

    and have a view like this(here I will be using reverse relation to fetch books from genre):

    def genre_book(request, pk):
         # will be using genre here to fetch all the books
         genre = Genre.objects.get(pk=pk)
         context = {
             'books': genre.book_set.all()  # using reverse relation to get the books
         }
         return render(request, 'some_template.html', context)
    

    Then you can link your view like this:

    class GenreTable(tables.Table):
         genre = tables.LinkColumn('books_genre_table', args=[A('pk')])
         class Meta:
            ...