Friends, I have a table (django-tables2) and a search filter called 'comment'. (django-filters)
I want to access the searched word inside the Table class. For example, inside the qs() event or somewhere else, I pass it to the request, so that I can access it on the other side in the Table class.
class CommentsView(LoginRequiredMixin, SingleTableMixin, FilterView):
model = Comments
queryset = Comments.objects.all().order_by('-id')
table_class = CommentTable
filterset_class = CommentFilter
Filter :
class CommentFilter(FilterSet):
class Meta:
model = Comments
fields = ['comment']
@property
def qs(self):
parent = super().qs
# here I want to pass it
search_key=self.data.get('comment')
return parent
The table class :
class CommentTable(tables.Table):
def render_comment(self, record):
# access here like self.request.GET.get('search_key')
return record.comment
After searching up and down and of course getting help from a friend, I found an answer and I will put it here so that if someone needs it in the future, it can be used :
First: In the filter class, I entered search_key as a property
def __init__(self, *args, **kwargs):
super(SearchCommentFilter, self).__init__(*args, **kwargs)
self.search_key = self.data.get('comment', '')
After that I read it and send it to table class in the view
def get_table(self, **kwargs):
table = super().get_table(**kwargs)
filterset = self.get_filterset(self.filterset_class)
search_key = getattr(filterset, 'search_key', None)
table.search_key = search_key
return table
Finally, I used it in the table class
def render_comment(self, record):
search_key = getattr(self, 'search_key', None)
return record.comment.replace(search_key, f"<mark>{search_key}</mark>")