I'm using Django endles-pagination to load the pages in infinite scroll. I also have some filters that filter the data according to the criteria (for eg, price slider filtering according to price). Now when the page loads, the filter right now filters only from the page loaded, though I want it to filter it from all the pages that have been or are to be loaded. Is there a way to do this (by making some ajax request or something)?
Any help on this would be great. Thanks a lot.
To filter the data you have to redefine get_queryset()
method in the views requesting the filtered query.
For example I request the current language in template to filter the Blog posts based on the language:
class Blog(AjaxListView):
context_object_name = "posts"
template_name = 'cgapp/blog.html'
page_template = 'cgapp/post_list.html'
def get_queryset(self):
if self.request.LANGUAGE_CODE == 'en': #request value of the current language
return News.objects.filter(language='en') #return filtered object if the current language is English
else:
return News.objects.filter(language='uk')
To filter the queryset based on the users input, you may refer to POST method:
from app.forms import BlogFilterForm
class Blog(LoginRequiredMixin, AjaxListView):
context_object_name = "posts"
template_name = 'blog/blog.html'
page_template = 'blog/post_list.html'
success_url = '/blog'
def get_queryset(self): # define queryset
queryset = Post.objects.all() # default queryset
if self.request.method == 'POST': # check if the request method is POST
form = BlogFilterForm(self.request.POST) # define form
if form.is_valid():
name = form.cleaned_data['name'] # retrieve data from the form
if name:
queryset = queryset.filter(name=name) # filter queryset
else:
queryset = queryset
return queryset
def get_context_data(self, **kwargs):
context = super(Blog, self).get_context_data(**kwargs)
context['form'] = BlogFilterForm() # define context to render the form on GET method
return context
def post(self, request, *args, **kwargs): # define post method
return super(Blog, self).get(request, args, kwargs)
The endless pagination should work fine.