1👍
✅
You need to keep track of your GET
params, update your view to be:
def discussion(request, discussion): # <<- view name and var name both are same which might cause issues
search_query = request.GET.get('q', '')
sort = request.GET.get('sort', '')
direction = request.GET.get('dir', 'asc')
if direction not in ['asc', 'desc']:
direction = 'asc'
topics_list = Topic.objects.all().filter(discussion__url=discussion)
discussion = Discussion.objects.get(url=discussion)
if search_query:
topics_list = topics_list.filter(
Q(title__icontains=search_query) |
Q(user__username__icontains=search_query)
)
if sort:
order_by = '{0}{1}'.format('-' if direction == 'desc' else '', sort)
topics_list = topics_list.order_by(order_by)
# rest of code
# pass search_query, sort and direction in context
context = {
'topics': topics,
'discussion': discussion,
'sort': sort,
'direction': direction,
'search_query': search_query,
}
return render(request, 'forum/forum_show_posts.html', context)
Now in template keep track of those params in both forms:
Search Form:
<form method="GET" action="">
<div class="input-group">
<input type="text" name="q" placeholder="Search..." value="{{ search_query }}" class="form-control">
<span class="input-group-btn">
<input class="btn btn-secondary" type="submit" value="Search">
</span>
</div>
<input type="hidden" name="sort" value="{{ sort }}" />
<input type="hidden" name="direction" value="{{ direction }}" />
</form>
Sort Form:
<div class="dropdown-menu">
<a class="dropdown-item disabled" href="#">Sort...</a>
<form method="GET" action="">
<div class="input-group">
<button class="dropdown-item" type="submit" name="sort" value="newest">Newest</button>
<button class="dropdown-item" type="submit" name="sort" value="oldest">Oldest</button>
<button class="dropdown-item" type="submit" name="sort" value="views">Views</button>
<button class="dropdown-item" type="submit" name="sort" value="comments">Comments</button>
<button class="dropdown-item" type="submit" name="sort" value="replies">Replies</button>
<button class="dropdown-item" type="submit" name="sort" value="name">Name</button>
</div>
<input type="hidden" name="search_query" value="{{ search_query }}" />
<input type="hidden" name="direction" value="{{ direction }}" />
</form>
</div>
Source:stackexchange.com